KTB
KTB

Reputation: 1529

Mongodb - find query based on an element of an array

I have the following type of document where I have to find instock elements based on a given value. i.e Return all instocks where ele = 5.

{"item":"journal",
 "instock":[
    { "warehouse":"A", "ele":[2,4,5] },
    { "warehouse":"C", "ele":[8,5,2] },
    { "warehouse":"F", "ele":[3] },
    { "warehouse":"K", "ele":[2,8,4] }
    ]
}

I tried to use $elemMatch but it just produces the first element.

db.inventory.find({"item": "journal"}, {"_id": 0, "item": 0, "instock":{$elemMatch: {"ele": {$in: [5]}}} })

But it just gives:

{ "instock" : [ 
    { "warehouse" : "A", "ele" : [ 2, 4, 5 ] }
]}

And the expectation is

{ "instock" : [ 
    { "warehouse" : "A", "ele" : [ 2, 4, 5 ] },
    { "warehouse" : "C", "ele" : [ 8, 5, 2 ] }
]}

How should I get the expected result?

Upvotes: 1

Views: 39

Answers (2)

Hussein Awala
Hussein Awala

Reputation: 5088

I suggest you to unwind the instock array, then filter the data, and finally if you want you can group the result by item to obtain the desired result.

Here is an exemple: solution

Upvotes: 0

turivishal
turivishal

Reputation: 36094

The $elemMatch or instock.$ will return first match document in find()'s projection,

You can use aggregation expression in projection from MongoDB 4.4, for your example use array $filter operator in projection,

db.collection.find({
  "item": "journal"
},
{
  instock: {
    $filter: {
      input: "$instock",
      cond: { $in: [5, "$$this.ele"] }
    }
  }
})

Playground


For the old version you can use aggregate() using above same operator.

Upvotes: 1

Related Questions