0

Unlike the other question someone asked where they wanted only one item returned. I HAVE one item returned and I need ALL of the matching objects in the array return. However the second object that matches my query is being completely ignored.

This is what one of the items in the item collection looks like:

     {
       name: "soda",
       cost: .50,
       inventory: [
             { flavor: "Grape",
               amount: 8 },
             { flavor: "Orange",
               amount: 4 },
             { flavor: "Root Beer",
               amount: 15 }
       ]
     }

Here is the query I typed in to mongo shell:

    Items.find({"inventory.amount" : { $lte : 10} } , { name : 1,  "inventory.$.flavor" : 1})

And here is the result:

    "_id" : ObjectId("59dbe33094b70e0b5851724c"),
    "name": "soda"
    "inventory" : [
           { "flavor" : "Grape",
             "amount" : 8,
           }
     ]

And here is what I want it to return to me:

    "_id" : ObjectId("59dbe33094b70e0b5851724c"),
    "name": "soda"
    "inventory" : [
           { "flavor" : "Grape",
             "amount" : 8
           },
           { "flavor" : "Orange",
             "amount" : 4
           }
     ]

I'm new to mongo and am dabbling to get familiar with it. I've read through the docs but couldn't find a solution to this though it's quite possible I overlooked it. I'd really love some help. Thanks in advance.

  • 1
    Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – s7vr Oct 11 '17 at 23:36
  • Use `Items.aggregate([ {$addFields: { inventory: {$filter: { input: '$inventory', as: 'res', cond: {$lte: ['$$res.amount', 10]} }} }} ])` – s7vr Oct 12 '17 at 01:33
  • Wow, i tried it in the shell and it worked. What you used is more advance than what I have learn so far so I have to figure out what each part means. The only thing is where do I put my projection in your code? The part where I tell it not to return the id and cost field. I was totally convinced nothing would work, I can't thank you enough. – Ari Bryant Oct 12 '17 at 02:12
  • You are welcome. Add `{$project:{_id:0, cost:0}} ` or change from `addFields` to `project` and include fields you want along with `inventory`. More here https://docs.mongodb.com/manual/reference/operator/aggregation/project/ – s7vr Oct 12 '17 at 04:55

1 Answers1

0

first u can get your result by this query

db.Items.find({"inventory.amount" : { $lte : 10} } , { name : 1,  "inventory.flavor" : 1 , "inventory.amount" : 1})
Nozar Safari
  • 505
  • 4
  • 17