0

This is my data:

{
    "_id": 1,
    "items": [
        [{"name": "a"}, {"size": 2}, {"color": "red"}],
        [{"name": "b"}, {"size": 4}, {"color": "blue"}],
        [{"name": "c"}, {"size": 6}, {"color": "pink"}]
    ]    
},
{
    "_id": 2,
    "items": [
        [{"name": "a"}, {"size": 3}, {"color": "black"}],
        [{"name": "e"}, {"size": 6}, {"color": "blue"}],
        [{"name": "g"}, {"size": 9}, {"color": "pink"}]
    ]    
}

And I need to do something like this:

db.foo.find({items.name: "a", items.color: "red"})

It's not working

4
  • Possible duplicate of MongoDB Query double nested documents in array Commented Apr 27, 2017 at 20:37
  • my collection is different. Commented Apr 27, 2017 at 21:05
  • try something like db.foo.find({ items: {$all: ["name": "a"], ["color": "red"]}}); Let me know if that works Commented Apr 27, 2017 at 21:12
  • It didn't work. I got an error -> Unexpected token : Commented Apr 27, 2017 at 23:59

2 Answers 2

0

For this, you could make use of the $elemMatch keyword.

db.foo.find({items: {$elemMatch: {name: "a", color: "red"} } });

That should allow to match on multiple fields of a document within an array.

Sign up to request clarification or add additional context in comments.

Comments

0

I found this solution:

db.foo.find({ 
    items: {
        $elemMatch: {
            $all: [
                {$elemMatch: {"name": "a"}},
                {$elemMatch: {"color": "red"}}
               ]
         }
    }
});

Thanks guys!!

Comments

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.