Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoDb $in with aggregate query

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
like image 827
Yoga Avatar asked Dec 08 '16 07:12

Yoga


People also ask

Is MongoDB good for aggregation?

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.

What is aggregate query MongoDB?

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.

What are the differences between using aggregate () and find () in MongoDB?

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.

Can we use count with aggregate function in MongoDB?

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.


2 Answers

The equivalent mongo query follows:

db.collection1.aggregate([
    { "$match": { 
        "name": { "$in": arrayList },
        "cond1": "false"
    } }, 
    { "$group": {
        "_id": "$name",
        "count": { "$sum": "$something" }
    } }
])
like image 173
chridam Avatar answered Nov 15 '22 07:11

chridam


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
})
like image 33
osama somy Avatar answered Nov 15 '22 08:11

osama somy