Kbalsamy
Kbalsamy

Reputation: 127

How to merge two fields into one field in MongoDB

Below are the product collection sample docs :

{ _id:'xxxxxxxxxxxx',
  name:'product 1'
 }
{ _id:'xxxxxxxxxxxx',
  name:'product 2'
 }

how to group id field value to name field value in mongodb?

Expected result :

[{'xxxxxxxxxxxx:'product1'},{'xxxxxxxxxxxx':'product2'}]

Upvotes: 2

Views: 703

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17935

You can try below aggregation queries :

On MongoDB version >= 4.2:

db.collection.aggregate([
  {
    $replaceWith: {
      $arrayToObject: [
        [
          {
            k: { $toString: "$_id" },
            v: "$name"
          }
        ]
      ]
    }
  }
])

Test : mongoplayground

On MongoDB version >= 4.0 :

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $arrayToObject: [
          [
            {
              k: { $toString: "$_id" },
              v: "$name"
            }
          ]
        ]
      }
    }
  }
])

Test : mongoplayground

Just in case if you've more fields & wanted to retain all of those in document in the final result then try this on MongoDB version >= 4.0 :

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          {
            $arrayToObject: [ [ { k: { $toString: "$_id" }, v: "$name" } ] ]
          },
          "$$ROOT"
        ]
      }
    }
  }
])

Test : mongoplayground

Note : As keys in an object must be of type string & can't hold type of ObjectId() We're converting _id value to string, if your _id is of type string then no need to use $toString operator.

Ref : aggregation-pipeline-stages

Upvotes: 2

Related Questions