2016-09-08 109 views
3

我有多個文檔數據: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" 
} 

我想根據我的多個條件來獲取數據:當運行條件1

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

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

我想下面的結果:

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

上面的查詢工作,爲第一條件&失敗其他。請幫幫我。

回答

2

對於第二個條件,你可以使用$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()方法返回與上述查詢相匹配的不同empIds陣列,如下所示:

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

上面的查詢工作爲「或」條件。我需要「和」。即Result僅返回兩個條件的完全匹配。 –