简体   繁体   中英

Mongodb Aggregate with nested subdocuments

I have a document looking like this:

{
  "_id": "some_uuid",
  "inv": {
    "food01": "id01",
    "food02": "id02",
    "food03": "id03"
  },
  "food": {
    "id01": {
      "n": "apple"
    },
    "id02": {
      "n": "banana"
    },
    "id03": {
      "n": "pear"
    }
  }
}

I want to use Mongodb Aggregate to retrieve the following output.

Expected Output

{
    "_id": "some_uuid",
  "inv": {
    "food01": "apple",
    "food02": "banana",
    "food03": "pear"
  }
}

Can someone guide me how to do this? Thank you!

One option is using $objectToArray to format these fields as arrays, which will allow to use $map and $filter to match them:

db.collection.aggregate([
  {$set: {inv: {$objectToArray: "$inv"}, food: {$objectToArray: "$food"}}},
  {
    $project: {
      inv: {$map: {
          input: "$inv",
          in: {
            k: "$$this.k",
            v: {
              $filter: {
                input: "$food",
                as: "food",
                cond: {$eq: ["$$this.v", "$$food.k"]}
              }
            }
          }
        }
      }
    }
  },
  {
    $project: {
      inv: {
        $map: {
          input: "$inv",
          in: {k: "$$this.k", v: {$first: "$$this.v.v.n"}}
        }
      }
    }
  },
  {$project: {inv: {$arrayToObject: "$inv"}}}
])

See how it works on the playground example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM