Home > front end >  Getting concrete elements by element field in mongoDB
Getting concrete elements by element field in mongoDB

Time:11-10

I know that by the title it is not very clear what is my problem, so let me explain it with an example. Let's suppose I have a collection in a mongo database called tweets whose elements look like this:

{
 "id": "tweet_id",
 "text": "this is the tweet's text",
 "user": {
          "id": "user_id",
          "name": "user_name",
         }
}

Let's suppose that we have 100 documents that look like that, and 10 users with diferent ids and names. How would look a query to know see the different user_id s that exist in the collection and their names? The result I want would look like this:

{"user_id1": "user_name1"}
{"user_id2": "user_name2"}
...
{"user_id10": "user_name10"}

Thank you for your help

CodePudding user response:

You can use this aggregation query:

  • First $group by user.id to get all differents user ids with the name.
  • And then use $replaceRoot with $arrayToObject to get the desired output format.
db.collection.aggregate([
  {
    "$group": {
      "_id": "$user.id",
      "name": {
        "$first": "$user.name"
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": [
          [
            {
              "k": "$_id",
              "v": "$name"
            }
          ]
        ]
      }
    }
  }
])

Example here

  • Related