mongoose 多条件MongoDB查询

lndjwyie  于 2022-11-24  发布在  Go
关注(0)|答案(4)|浏览(214)

我的数据包含多个文档:

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

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

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

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

当运行条件1时,我希望得到以下结果:

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

运行第二个条件时:

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

我希望通过一个查询得到上面结果,
目前我使用下面聚合查询,

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

以上第一个条件的查询工作&其他条件的查询工作失败。请帮助我。

mrfwxfqh

mrfwxfqh1#

对于第二个条件,可以在查询中使用**$in**运算符,如下所示:

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的数组,如下所示:

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

velaa5lx2#

如果要查找AND运算符
此示例检查字段是否存在为空

db.getCollection('TheCollection').find({
    $and: [
        {'the_key': { $exists: true }},
        {'the_key': null}
    ]
})

本示例检查字段是否具有'value1'OR'value2'

db.getCollection('TheCollection').find({
    $or: [
        {'the_key': 'value1'},
        {`the_key': 'value2'}
    ]
})

仅检查空值时,返回包含不存在的字段以及值为空的字段

db.getCollection('TheCollection').find({'the_key': null})
bnl4lu3b

bnl4lu3b3#

您可以使用mongo db $or运算符。

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

您可以在数组中传递条件。
更多参考see mongo docs

daolsyd0

daolsyd04#

1.显示“StudName”中的值为“Ajay Rathod”的文档。
数据库.学生.find({name:“ajay rathod”})

{ "_id" : ObjectId("5fdd895cd2d5a20ee8cea0de"), "

1.仅检索学生姓名和年级。
db.学生.find({},{姓名:1,年级:1,_id:0})

{ "name" : "dhruv", "grade" : "A" }
{ "name" : "jay", "grade" : "B" }
{ "name" : "abhi", "grade" : "C" }
{ "name" : "aayush", "grade" : "A" }
{ "name" : "sukhdev", "grade" : "B" }
{ "name" : "dhruval", "grade" : "B" }
{ "name" : "ajay rathod", "grade" : "D" }

相关问题