8

How do I write an $in query along with aggregate in mongoDB? I want to write an equivalent mongoDB query for the SQL below

SELECT name,count(something) from collection1
where name in (<<list of Array>>) and cond1 = 'false'
group by name

2 Answers 2

23

The equivalent mongo query follows:

db.collection1.aggregate([
    { "$match": { 
        "name": { "$in": arrayList },
        "cond1": "false"
    } }, 
    { "$group": {
        "_id": "$name",
        "count": { "$sum": "$something" }
    } }
])
Sign up to request clarification or add additional context in comments.

2 Comments

What works for me is name: { "$in": arrayList } (and not "name")
Hi, question... How can I send "$in": <all>, if I can do that?
4

Suppose you have an Schema with field tags

{
 tags: ['banana', 'apple', 'orange']
}

and you want find out apple inside tags with aggregate function then

const keywords = "apple"; // req.body.keywords

const filter =  { $match : { tags: {$in : [keywords] } }}

Schema.aggregate(filter).then(result=>{
 // You can do what you want with result
})

1 Comment

from MongdoDB: $in operator matches values in array as long as at least one element matches -> mongodb.com/docs/manual/reference/operator/query/in

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.