Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Retrieve only the queried element in an object array in MongoDB collection

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 898
    Comment on it

    Suppose we want retrieve only the queried element in an object array then we need to perform mongo query like below. Let me explain with this help of example.

    {
     _id: 4,
     zipcode: "63109",
     students: [
                  { name: "ankit", school: 99, age: 11 },
                  { name: "amit", school: 99, age: 12 },
               ]
    }
    

    if we want the above document filtered with only array item age =12:

    $elemMatch

    We will use $elemMatch operator for this.

    The $elemMatch operator limits the contents of an field from the query return the first element matching the $elemMatch condition.

    db.schools.find( {"students.age": "19"}, 
                {students: {$elemMatch: {age: "12"}}});
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: