0

I'm trying to perform a simple find using MongoDB, I'm new on it, so I don't know what is wrong, but it seems that it's always bringing all the results without filtering it.

You can run the code here and see what is happening: https://mongoplayground.net/

Collection - Paste it here https://mongoplayground.net/ - FIRST Text Area

[
  {
    "collection": "collection",
    "count": 10,
    "content": [
      {
        "_id": "apples",
        "qty": 5
      },
      {
        "_id": "bananas",
        "qty": 7
      },
      {
        "_id": "oranges",
        "qty": {
          "in stock": 8,
          "ordered": 12
        }
      },
      {
        "_id": "avocados",
        "qty": "fourteen"
      }
    ]
  }
]

Find - Paste it here https://mongoplayground.net/ - SECOND Text Area

db.collection.find({
  "content.qty": 5
})

Check the results and you will see the entire JSON as a result. What Am I doing wrong? Thanks!

2 Answers2

0

You can use $filter with $project after your $match in order to get just one item from the array:

db.collection.aggregate([
  { $match: { "content.qty": 5 }},
  {
    $project: {
      collection: 1,
      count: 1,
      content: {
        $filter: {
          input: "$content",
          as: "item",
          cond: { $eq: [ "$$item.qty", 5 ]
          }
        }
      }
    }
  }
])

Without having to unwind etc. You are getting all since $find returns the first document which matches and in your case that is the main doc.

See it working here

Akrion
  • 18,117
  • 1
  • 34
  • 54
0

First, the query is bringing back what it should do. it bring you the document that satisfy your query, try to add element or more in the array you search in to see the difference. Secondly, what you want to reach - to get only the specific elements in the nested array - can be done by aggregation you can read in it more here: https://docs.mongodb.com/manual/aggregation/

Shorbagy
  • 526
  • 3
  • 4