Some Java Guy Some Java Guy - 25 days ago 6
JSON Question

mongo find function mismatch

Mongo version :

3.2.8


My sample json is as below

enter image description here

My query to fetch
name
equal to
apple
doesn't work.

db.collection.find( { "products.foods.name": "apple" } )


Instead it fetches all the records, strange?

Neither does the $eq, $lt or $gt work. They result with the entire data.

db.aggregation.find( { "products.foods.min_price": {$eq:10} } )


Thanks in advance.

Answer

The solution is to n $unwind both the arrays.

db.foods.aggregate([   
    { $unwind : "$products" },
    { $unwind : "$products.foods" },
    { $match  : { "products.foods.min_price": 10        }}
])