MongoDB:与子数组中的对象不同的值

时间:2019-05-13 06:40:33

标签: database mongodb mongodb-query aggregation-framework

我有一些结构类似的文件。例如:

{ 'observer': 'machine1', 
  'seen': [ 
     {'page1': ['/link1', '/link3']},
     {'page2': ['/link4', '/link1']},
}

{ 'observer': 'machine2', 
  'seen': [ 
     {'page3': ['/link2']},
     {'page1': ['/link5']},
}

我正在尝试获取数组中所有不同键和值的列表,并按observer分组。在理想的世界中,它看起来像:

{'machine1': ['/link1', '/link3', '/link4'], 'machine2': ['/link2', '/link5'] }

{'machine1': ['page1', 'page2'], 'machine2': ['page1', 'page3']}

我知道我可以使用$ aggregate和$ group来基于子列表获取唯一值,但是我不确定如何处理对象列表并获取其键和值。

1 个答案:

答案 0 :(得分:1)

您可以使用以下汇总

db.collection.aggregate([
  { "$unwind": "$seen" },
  { "$addFields": {
    "seen": {
      "$objectToArray": "$seen"
    }
  }},
  { "$unwind": "$seen" },
  { "$unwind": "$seen.v" },
  { "$group": {
    "_id": "$observer",
    "links": { "$addToSet": "$seen.v" }
  }}
])

MongoPlayground

如果您同时需要pageslinks

db.collection.aggregate([
  { "$unwind": "$seen" },
  { "$addFields": {
    "seen": {
      "$objectToArray": "$seen"
    }
  }},
  { "$unwind": "$seen" },
  { "$unwind": "$seen.v" },
  { "$facet": {
    "pages": [
      { "$group": {
        "_id": "$observer",
        "pages": { "$addToSet": "$seen.v" }
      }}
    ],
    "links": [
      { "$group": {
        "_id": "$observer",
        "links": { "$addToSet": "$seen.k" }
      }}
    ]
  }}
])

MongoPlayground

如果您需要更多增强功能

db.collection.aggregate([
  { "$unwind": "$seen" },
  { "$addFields": {
    "seen": {
      "$objectToArray": "$seen"
    }
  }},
  { "$unwind": "$seen" },
  { "$unwind": "$seen.v" },
  { "$facet": {
    "pages": [
      { "$group": {
        "_id": "$observer",
        "pages": { "$addToSet": "$seen.v" }
      }}
    ],
    "links": [
      { "$group": {
        "_id": "$observer",
        "pages": { "$addToSet": "$seen.k" }
      }}
    ]
  }},
  { "$project": {
    "pages": {
      "$map": {
        "input": "$pages",
        "in": {
          "$let": {
            "vars": {
              "links": {
                "$arrayElemAt": [
                  "$links",
                  { "$indexOfArray": ["$links._id", "$$this._id"] }
                ]
              }
            },
            "in": {
              "_id": "$$this._id",
              "pages": "$$this.pages",
              "links": "$$links.links"
            }
          }
        }
      }
    }
  }},
  { "$unwind": "$pages" },
  { "$replaceRoot": { "newRoot": "$pages" }}
])

MongoPlayground