mongodb 具有多个条件的MongoDB查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39389823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:49:28  来源:igfitidea点击:

MongoDB query with multiple conditions

mongodbmongoose

提问by Amrut Gaikwad

I have data with multiple documents :

我有多个文件的数据:

{
 "_id" : ObjectId("57b68dbbc19c0bd86d62e486"),
 "empId" : "1"
 "type" : "WebUser",
 "city" : "Pune"
}
{
 "_id" : ObjectId("57b68dbbc19c0bd86d62e487"),
 "empId" : "2"
 "type" : "Admin",
 "city" : "Mumbai"
}
{
 "_id" : ObjectId("57b68dbbc19c0bd86d62e488"),
 "empId" : "3"
 "type" : "Admin",
 "city" : "Pune"
}
{
 "_id" : ObjectId("57b68dbbc19c0bd86d62e489"),
 "empId" : "4"
 "type" : "User",
 "city" : "Mumbai"
}

I want to get data according to my multiple conditions :

我想根据我的多个条件获取数据:

condition 1:- {"type" : "WebUser", "city" : "Pune"}

condition 2:- {"type" : "WebUser", "city" : "Pune"} & {"type" : "User", "city" : "Mumbai"}

I want below result when run condition 1 :

当运行条件 1 时,我想要以下结果:

    {
     "_id" : ObjectId("57b68dbbc19c0bd86d62e486"),
     "empId" : "1"
     "type" : "WebUser",
     "city" : "Pune"
    }

When I run second condition :

当我运行第二个条件时:

{
  "_id" : ObjectId("57b68dbbc19c0bd86d62e486"),
  "empId" : "1"
  "type" : "WebUser",
  "city" : "Pune"
}
{
  "_id" : ObjectId("57b68dbbc19c0bd86d62e489"),
  "empId" : "4"
  "type" : "User",
  "city" : "Mumbai"
}

I want above result by one query,

我想通过一个查询获得以上结果,

Currently I am using below aggregate query,

目前我正在使用以下聚合查询,

 db.emp.aggregate([
     { $match: { '$and': [
         {"type" : "WebUser", "city" : "Pune"}, 
         {"type" : "User", "city" : "Mumbai"}
     ] } },
     { $group: { _id: 1, ids: { $push: "$empId" } } }
 ])

Above query work for first condition & fails for other. Please help me.

以上查询适用于第一个条件,而其他查询失败。请帮我。

回答by chridam

For the second condition, you can use the $inoperator in your query as:

对于第二个条件,您可以$in在查询中使用运算符作为:

db.emp.find({
    "type" : { "$in": ["WebUser", "User"] },
    "city" : { "$in": ["Pune", "Mumbai"] }
})

If you want to use in aggregation:

如果要在聚合中使用:

 db.emp.aggregate([
     { 
        "$match": {
            "type" : { "$in": ["WebUser", "User"] },
            "city" : { "$in": ["Pune", "Mumbai"] }
        }
     },
     { "$group": { "_id": null, "ids": { "$push": "$empId" } } }
 ])

or simply use the distinct()method to return an array of distinct empIds that match the above query as:

或者简单地使用该distinct()方法返回与上述查询匹配的不同 empId 的数组,如下所示:

var employeeIds = db.emp.distinct("empId", {
    "type" : { "$in": ["WebUser", "User"] },
    "city" : { "$in": ["Pune", "Mumbai"] }
});