Home > database >  mongoose and mogodb get all country and users associated with country
mongoose and mogodb get all country and users associated with country

Time:10-25

So i have a list of posts data that look like this

[{user: 'Bob', country: 'USA'}
{user: 'Kim', country: 'Mexico'}
{user: 'Darren', country: 'Mexico'}
{user: 'Joe', country: 'Mexico'}]
etc....

I want my to get my data like

[{Mexico: {'Kim', 'Darren', 'Joe'}, USA: {'Bob'}}]

This is what i got so far but i'm a bit confused by the docs and the posts here are pretty outdated. Any help would be greatly appreciated.

Post.aggregate([
      { $group: { _id: "$country", users: { $in: "$posts" } } },
    ]);

CodePudding user response:

$group $addToSet

db.collection.aggregate([
  {
    "$group": {
      "_id": "$country",
      "users": {
        "$addToSet": "$user"
      }
    }
  }
])

result

[
  {
    "_id": "Mexico",
    "users": [
      "Kim",
      "Darren",
      "Joe",
      "Bob"
    ]
  },
  {
    "_id": "USA",
    "users": [
      "Bob"
    ]
  }
]

mongoplayground

CodePudding user response:

You're almost to the answer. You need $push user field to users.

db.collection.aggregate({
  $group: {
    _id: "$country",
    users: {
      $push: "$user"
    }
  }
})

Sample Mongo Playground ($push)


Use $addToSet to add value to array without duplicate.

The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.

db.collection.aggregate({
  $group: {
    _id: "$country",
    users: {
      $addToSet: "$user"
    }
  }
})

Sample Mongo Playground ($addToSet)

  • Related