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
This is similar to the basic aggregation available in SQL with the GROUP BY clause and COUNT, SUM and AVG functions. MongoDB Aggregation goes further though and can also perform relational-like joins, reshape documents, create new and update existing collections, and so on.
Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result.
With aggregate + $match, you get a big monolithic BSON containing all matching documents. With find, you get a cursor to all matching documents. Then you can get each document one by one.
MongoDB $count Aggregation First, we invoke the $count operator and then specify the string. In this syntax, 'the_string' represents the label or the name of the output field. It must be non-empty and cannot start with a dollar sign '$' or dot '. ' character.
The equivalent mongo query follows:
db.collection1.aggregate([
{ "$match": {
"name": { "$in": arrayList },
"cond1": "false"
} },
{ "$group": {
"_id": "$name",
"count": { "$sum": "$something" }
} }
])
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With