0

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,
                  ]}}})

1 Answer 1

1
  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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, @yong. There is only one small change for real-time execution. k: { $toString: '$_id' }. _id needs to convert into a string as arrayToObject does not convert objected type value to key.
Ya, key must be in string. You're welcome. =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.