Some Java Guy
Some Java Guy

Reputation: 5118

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.

Upvotes: 0

Views: 259

Answers (4)

Some Java Guy
Some Java Guy

Reputation: 5118

The solution is to n $unwind both the arrays.

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

Upvotes: 0

Clement Amarnath
Clement Amarnath

Reputation: 5466

If your entire document is in an _id, then if the query matches db.collection.find( { "products.foods.name": "apple" } ) even though it is a document in foods array the entire document will be displayed, so that you are getting other fruits as well.

To Solve this first use $unwind the aggregation pipeline to break the foods array into individual documents and then use $match.

Please refer this post, It is a similar question and I have answered the steps in detail in that post.

Upvotes: 1

Mital Gajjar
Mital Gajjar

Reputation: 234

Try with this:db.Exercise.aggregate([ {$match: {'products.foods.min_price': 10}}])

Upvotes: 0

Kumar Sourav
Kumar Sourav

Reputation: 419

Try with this:

db.test.aggregate([
    {$match: {'products.foods.name': 'apple'}}])

Taken from Retrieve only the queried element in an object array in MongoDB collection

You can try other examples from that post.

Upvotes: 0

Related Questions