我在集合中有这些类型的文档:
{"action": "add", "text": "a"},
{"action": "remove", "text": "a"},
{"action": "add", "text": "a"},
{"action": "add", "text": "b"},
{"action": "remove", "text": "b"},
{"action": "add", "text": "c"},
现在我想得到所有这些条件存在的所有条目:
text
匹配我的参数,例如a
action
等于add
条目的数量大于1的条目,然后action
的数量等于remove
条目鉴于上面的示例数据,action
a
或c
的查询应该产生结果,而b
不会产生任何结果。
需要得到MongoDb 3.4的支持。
除了Veeram解决方案,您还可以对文本字段进行分组(无需匹配操作),以便您可以按预期获得响应。
鉴于上面的示例数据,查询操作a或c应该产生结果,而b应该不产生任何结果。
db.collection.aggregate([
{"$group":{
"_id":"$text",
"action_add":{"$sum":{"$cond":[{"$eq":["$action","add"]},1,0]}},
"action_remove":{"$sum":{"$cond":[{"$eq":["$action","remove"]},1,0]}},
"data":{"$push":"$$ROOT"}
}},
{"$addFields":{"diff":{"$subtract":["$action_add","$action_remove"]}}},
{"$match":{"diff":1}},
{"$unwind":"$data"},
{"$replaceRoot":{"newRoot":"$data"}}
])