Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDb查询$or$and_Mongodb - Fatal编程技术网

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