Skip to main content

Example for elemMatch

Find all documents against array fields which matches any of the input


Suppose, I have a collection "StockUsers" like this.

{
    "user":"kiran",
    "stocksPurchased":["hdfc","sbi","icici"]
}

{
    "user":"vanaja",
    "stocksPurchased":["hdfc","idbi","pnb"]
}

{
    "user":"karthika",
    "stocksPurchased":["idfc","idbi"]
}

{
    "user":"venkat",
    "stocksPurchased":["citi"]
}


Now, If i want to query the users who purchased any of the given stocks.

Ex: Retrieve all users who purchased idfc or pnb

Query:

db.StockUsers.aggregate([
{
   "$match": {
       "stocksPurchased": {"$elemMatch":{"$in":["idfc","pnb"]}}
   }
}
])

Response:

{
    "user":"vanaja",
    "stocksPurchased":["hdfc","idbi","pnb"]
}

{
    "user":"karthika",
    "stocksPurchased":["idfc","idbi"]
}

Conclusion

Use elemMatch to query on array fields to which matches on ANY given input.

Comments

Popular posts from this blog

Finding documents using in and not

How to query for documents where field1 contains set of values and  field2 does not contain specified value? db.getCollection('Test').aggregate( [ {             "$match" : {                "field1" : {                    "$in" : [                        "92b445e1-86b0-41d3-9b14-adc22cbec7b1" ,                     "92b445e1-86b0-41d3-9b14-adc22cbec7b2"                 ]             } ,             "field2" : {                    "$not" : {...