Home > OS >  How to convert Mongo query array result into flatten object and key should be _id
How to convert Mongo query array result into flatten object and key should be _id

Time:01-26

How to convert mongo query result into flatten object.

Current result:

[
  {
    "_id": "61ef7e5497c9912ac1e56404",
    "name": "Mark",
    "age": 20,
    "isMinor": true
  },
  {
    "_id": "61ef7e5497c9912ac1e56404",
    "name": "Sam",
    "age": 22,
    "isMinor": false
  }
]

Excepted output:

[
  {
    "61ef7e5497c9912ac1e56404": {
      "_id": "61ef7e5497c9912ac1e56404",
      "name": "Mark",
      "age": 20,
      "isMinor": true
    },
    "61ef7e5497c9912ac1e56404": {
      "_id": "61ef7e5497c9912ac1e56404",
      "name": "Sam",
      "age": 22,
      "isMinor": false
    }
  }
]

I wanted to do this using aggregation query itself.

My current query:

Users.aggregate({$addField:{isMinor:{ $cond: [
                    { $gt: ['$age', 20] },
                    true, false,
                  ]}}})

CodePudding user response:

  1. $group - Group the document and add the users field which holds the key-value pair (key: id, value: document) array. This stage will return only a single document.
  2. $replaceWith - Replaces the input document with the specified document. This stage will output the document in key-value pair.
db.collection.aggregate([
  // Previous stages
  {
    $group: {
      _id: null,
      users: {
        $push: {
          k: { $toString: "$_id" },
          v: "$$ROOT"
        }
      }
    }
  },
  {
    "$replaceWith": {
      $arrayToObject: "$users"
    }
  }
])

Sample Mongo Playground

  •  Tags:  
  • Related