1

Supposed I have a mongo document that looks similar to the following:

{
   'foo':1
   'listOfLists' : [ [1,2],[3,4] ]
}

(Yes I am aware this isn't how it "really" looks but it should be simple enough for explanation purposes.)

If I wanted to write a query that would check to see if the listsOfLists list object contains the combination of [3,4], how could I go about doing that?

Could I do something like

collection.find({'listsOfLists' : {'$elemMatch' : [3,4] } })
0

1 Answer 1

1
collection.find({ 'listsOfLists': [3,4] }).

It's just a "direct match" on the property. MongoDB will look at each array element automatically. You don't need $elemMatch here.

If you were to use it, you need an operator expression, such as $eq:

collection.find({ 'listsOfLists': { '$elemMatch': { '$eq': [3,4] } } }).

But that of course is not required unless there are "two or more" conditions that actually need to match on the array elements. Which is what $elemMatch is actually for.

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

2 Comments

So, in a related item. Could I use $elemMatch to check to see if just the First element in a list matches a query? Something like { '$elemMatch' : { '$eq' : 3} }
@K.Niemczyk That would actually be Another Question to Ask, but it is one with a logical answer. Post another question here if you cannot work it out.

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.