首页 > 解决方案 > 根据条件查找和计算 mongo 数组中的重合

问题描述

想象一下,我有一组类似于以下内容的文档:

{
_id :ObjectId("45645645gdfgdfgdf"),
article:"article one",
topic:["config","develop","show"],
keys[
    {subject:"one",object"abc"},
    {subject:"one",object"def"},
    {subject:"two",object"ghi"},
    {subject:"four",object"jkl"},
    {subject:"four",object"mnl"},
    {subject:"four",object"mnl"},
]
},
{
_id :ObjectId("45645645gdfgdfgdf"),
article:"article two",
topic:["config","installing"],
keys[
    {subject:"one",object"abc"},
    {subject:"one",object"def"},
    {subject:"two",object"ghi"},
    {subject:"two",object"jkl"},
]
},
{
_id :ObjectId("45645645gdfgdfgdf"),
article:"article three",
topic:["config","installing"],
keys[
    {subject:"five",object"abc"},
    {subject:"five",object"def"},
    {subject:"two",object"ghi"},
    {subject:"two",object"jkl"},
]
}

我想根据条件计算数组中的每个主题,按主题过滤,例如,假设我按主题搜索:“config”和主题:[“one”,“four”] 结果需要是

{article :"article one", sum:5},{article :"article two", sum:2}

提前谢谢

标签: mongodbaggregation-framework

解决方案


You can use below aggregation.

db.colname.aggregate([
  {"$match":{"topic":"config","subject":{"$in":["one","four"]}}},
  {"$project":{
    "article":1,
    "sum":{
      "$size":{
        "$filter":{
          "input":"$keys",
          "cond":{"$in":["$$this.subject",["one","four"]]}
        }
      }
    }
  }}
])

推荐阅读