【问题标题】:mongodb, lookup by hash keymongodb,通过哈希键查找
【发布时间】:2019-08-06 06:47:18
【问题描述】:

我有一个这样的收藏:

  • 类别:
{_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}}

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

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework mongoid6


    【解决方案1】:

    您可以将以下聚合与 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"
        }
      }}
    ])
    

    MongoPlayground

    【讨论】:

    • 酷,但我使用的是 mongo 3.4 版本,我无法在查询中使用“管道”。有什么办法可以解决它
    • 太棒了!您应该保留两个版本的答案。这将帮助很多寻找此案例的人
    • 太好了! @Ashh,为我工作。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    相关资源
    最近更新 更多