如果我正确理解你的问题,你想返回从对象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字段,您可以获取对象满足它的每个条件的信息。我希望这是你想要的。