使用聚合查询的mongoDb $ in

时间:2016-12-08 07:35:38

标签: mongodb mongodb-query aggregation-framework

如何在mongoDB中编写$in查询和聚合?我想为下面的SQL编写一个等效的mongoDB查询

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

2 个答案:

答案 0 :(得分:4)

等效的mongo查询如下:

db.collection1.aggregate([
    { "$match": { 
        "name": { "$in": arrayList },
        "cond1": "false"
    } }, 
    { "$group": {
        "_id": "$name",
        "count": { "$sum": "$something" }
    } }
])

答案 1 :(得分:2)

假设你有一个带有字段标签的架构

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

然后你想找出带有聚合函数的标签内的苹果

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
})