如果我正確理解你的問題,你想返回從對象mongo集合並將信息附加到每個滿足條件的對象,而不是。假設我們有一個mongodb集合人員,其中的對象具有firstName,lastName和birthYear字段。我們可以利用這個聚集
db.person.aggregate([
{
$project : {
firstName : "$firstName",
lastName : "$lastName",
birthYear : "$birthYear",
matchCondition1 : { $cond: { if: { $eq : [ "$firstName" , "Novak" ] }, then: 200 , else: 100 }} ,
matchCondition2 : { $cond: { if: { $eq : [ "$lastName" , "Djokovic" ] }, then: 20 , else: 10 }} ,
matchCondition3 : { $cond: { if: { $eq : [ "$birthYear" , 1987 ] }, then: 2 , else: 1 }}
}
},
{
$project : {
firstName : "$firstName",
lastName : "$lastName",
birthYear : "$birthYear",
matchConditions : { $sum : [ "$matchCondition1", "$matchCondition2", "$matchCondition3" ] }
}
}
]);
結果會是什麼樣子: {姓: 「諾瓦克」,名字: 「德約科維奇」,birthYear: 「1987」,matchConditions:222}
{姓:「諾瓦克」,名字: 「Petrovic的」,birthYear: 「1987」,matchConditions:212}
{姓: 「諾瓦克」,名字: 「Petrovic的」,birthYear: 「1989」,matchConditions:211}
{名字:「羅傑」,姓氏:「費德勒」,出生年:「1981」, matchConditions:111}
然後從matchCondition字段,您可以獲取對象滿足它的每個條件的信息。我希望這是你想要的。