Search code examples
mongodbnosql-aggregation

MongoDB Aggregate - Group certain items in document array


I'm quite new on MongoDB

Having a document like:

"_id":0001
"Name": "John"
"Contacts": [
{
    "Person" : [
    {
        "User" : {

            "_id" : ObjectId("5836b916885383034437d230"),
            "Name": "Name1",
            "Age" : 25,             
        }
    },
    {
        "User" : {
            "_id" : ObjectId("2836b916885383034437d230"),
            "Name": "Name2",
            "Age" : 30,             
        }
    },
    {
        "User" : {
            "_id" : ObjectId("1835b916885383034437d230"),
            "Name": "Name3",
            "Age" : 31,             
        }
    },
 }

which is the best way to get an output with the information of the Contacts with age greater or equal than 30 years?

Output should like:

{_id: "John", "ContactName":"Name2", "Age":30  }
{_id: "John", "ContactName":"Name3", "Age":31  }

Is aggregation the best way to do it, or it can be done by using a simple "find" statement?


Solution

    • $match
    • $unwind
    • $unwind
    • $match
    • $project
    db.collection.aggregate([
      {
        "$match": {
          "Contacts.Person.User.Age": {
            "$gte": 30
          }
        }
      },
      {
        "$unwind": "$Contacts"
      },
      {
        "$unwind": "$Contacts.Person"
      },
      {
        "$match": {
          "Contacts.Person.User.Age": {
            "$gte": 30
          }
        }
      },
      {
        "$project": {
          "_id": "$Name",
          "ContactName": "$Contacts.Person.User.Name",
          "Age": "$Contacts.Person.User.Age"
        }
      }
    ])
    

    mongoplayground