0

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?

1 Answer 1

2

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" } } } 
    ]}
)
Sign up to request clarification or add additional context in comments.

2 Comments

thx! p.s. do you think it is the optimal data schema for this kind of search? or is it better to make the schema as [{"f1" : "val12"},{f2: "val22"}] ?
Can you please answer this question- stackoverflow.com/questions/67600862/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.