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
Post a Comment