MongoDb查询$or$and
我收集了以下类型的文档:MongoDb查询$or$and,mongodb,Mongodb,我收集了以下类型的文档: {"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", "text": "a"},
{"action": "remove", "text": "a"},
{"action": "add", "text": "a"},
{"action": "add", "text": "b"},
{"action": "remove", "text": "b"},
{"action": "add", "text": "c"},
现在我想获取所有存在这些条件的条目:
与我的参数匹配,例如text
a
- 仅获取
等于操作
条目数大于添加
等于操作
条目数的条目删除
操作a
或c
应产生结果,而b
不应产生结果
MongoDb 3.4需要支持。除了Veeram解决方案,您还可以在文本字段上分组(无需匹配操作),以便按照预期获得响应
给定see示例数据,对操作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"}}
])