ppn029012
ppn029012

Reputation: 570

How to query objects in array with multiple criteria in MongoDB?

Here is my data

// Data 1
{
  name : 111, 
  factors : 
  [
    {name:"f1", value:"dog", unit : "kg"},
    {name:"f2", value:"0"},
    {name: "f3", value:"rain"}
  ]
},
// data2
{
  name : 112, 
  factors : 
  [
    {name:"f1", value:"cat", unit : "g"},
    {name:"f2", value:"13"},
    {name: "f3", value:"rain"}
  ]
}
// more data ...

I would like to find the one with f3=rain, and f1=cat.

I have tried

query = {
  factors : {
    $elemMatch : 
       [
          {name: "f1", value:"cat"},
          {name: "f3", value: "rain"}
       ]
}, 

But there is error saying, Error: error: { "$err" : "$elemMatch needs an Object", "code" : 12517 }

What should I do to construct that query?

Upvotes: 0

Views: 1781

Answers (1)

Atish
Atish

Reputation: 4427

You need to use the $and logical query operator

db.collection.find(
    { $and: [
        { "factors": { $elemMatch: { "name": "f1", "value": "cat" } } }, 
        { "factors": { $elemMatch: { "name": "f3", "value": "rain" } } } 
    ]}
)

Upvotes: 2

Related Questions