4

我有一个这样的集合:

  • 类别:
{_id: Object:Id(...), code: 'drink', name: 'Soft Drink and Beer'}
{_id: Object:Id(...), code: 'fast-food', name: 'Burger and Chicken Fry'}
  • 组人:
{_id: Object:Id(G1), categories: {'drink' => 5, 'fast-food' => 3}}
{_id: Object:Id(G2), categories: {'drink' => 2}}

我真正想要的愿望输出:

{_id: Object:Id(G1), categories: {'Soft Drink and Beer' => 5, 'Burger and Chicken Fry' => 3}}
{_id: Object:Id(G2), categories: {'Soft Drink and Beer' => 2}}

我尝试了很多方法,但没有运气。你有这个案例的经验吗?

4

1 回答 1

4

您可以将以下聚合与 MongoDB 3.6及更高版本一起使用

db.GroupPeople.aggregate([
  { "$addFields": { "categories": { "$objectToArray": "$categories" }}},
  { "$unwind": "$categories" },
  { "$lookup": {
    "from": "Category",
    "let": { "category": "$categories.k" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$$category", "$code"] }}}
    ],
    "as": "category"
  }},
  { "$unwind": "$category" },
  { "$group": {
    "_id": "$_id",
    "categories": {
      "$push": {
        "k": "$category.name",
        "v": "$categories.v"
      }
    }
  }},
  { "$project": {
    "categories": {
      "$arrayToObject": "$categories"
    }
  }}
])

以及3.4.4及以上版本

db.GroupPeople.aggregate([
  { "$addFields": { "categories": { "$objectToArray": "$categories" }}},
  { "$unwind": "$categories" },
  { "$lookup": {
    "from": "Category",
    "localField": "categories.k",
    "foreignField": "code",
    "as": "category"
  }},
  { "$unwind": "$category" },
  { "$group": {
    "_id": "$_id",
    "categories": {
      "$push": {
        "k": "$category.name",
        "v": "$categories.v"
      }
    }
  }},
  { "$project": {
    "categories": {
      "$arrayToObject": "$categories"
    }
  }}
])

Mongo游乐场

于 2019-08-06T08:03:38.813 回答