具有多个条件的MongoDB查询 [英] MongoDB query with multiple conditions

查看:62
本文介绍了具有多个条件的MongoDB查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个文档的数据:

{
 "_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"}

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

I want below result when run condition 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.

推荐答案

对于第二种情况,可以使用 $in 运算符在您的查询中为:

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

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

如果要在聚合中使用:

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

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

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

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

这篇关于具有多个条件的MongoDB查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆