【问题标题】:Find and count coincidences in mongo array based on a condition根据条件查找和计算 mongo 数组中的重合
【发布时间】:2018-09-14 06:48:49
【问题描述】:

想象一下,我有一组类似的文档:

{
_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}

提前考虑

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您可以使用以下聚合。

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

    【讨论】:

    • 谢谢,这段代码帮助我理解了mongo的查询思路
    猜你喜欢
    • 2021-04-23
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    相关资源
    最近更新 更多