0

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?

1 Answer 1

1
  • $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

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

Comments

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.