1

I want to select an object within an array with id condition. In the below img i want to select [0].

enter image description here

db.users.find({"injury._id": ObjectId("537233061845d2ec10000071")})

Thankx for Help.

4
  • Can I please implore you to stop posting screenshots. They are horrible to try and read and data ( which you have at least posted some text this time ) is better represented as text so people can actually use it Commented May 21, 2014 at 10:04
  • With that out of the way. What is your actual question? Do you want to select an array element with an _id value or do you want to select the index 0 of an array? And then do what? Commented May 21, 2014 at 10:05
  • I want to select array element with _id... Commented May 21, 2014 at 10:06
  • You are with the query you show above. You mean something else perhaps? Please clarify what you mean by editing your question. Commented May 21, 2014 at 10:07

1 Answer 1

2

I'm guessing here that you want to only see the selected array element in the document you are searching for. Use projection:

db.users.find(
    { "injury._id": ObjectId("537233061845d2ec10000071")},
    { "injury.$": 1 }
)

That just returns the matching element rather than all of them.

If you expect more than one match ( unlikely with an ObjectId, but for future reference ) then use the .aggregate() method instead:

db.users.aggregate([

    // Match documents first, helps reduce the pipeline
    { "$match": {
       "injury._id": ObjectId("537233061845d2ec10000071")
    }},

    // Unwind the array
    { "$unwind": "$injury" },

    // Actually match the elements
    { "$match": {
       "injury._id": ObjectId("537233061845d2ec10000071")
    }},

    // Group back if you really want arrays
    { "$group": {
        "_id": "$_id",
        "injury": { "$push": "$injury" },
        // and use "$first" for any other fields
    }}
])

So now you know what to do when you come up against that one as well.

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

2 Comments

Thankx...Works good...next time i will try to post it without screenshots..:)
@Anup Thankyou. And there you also have the basic example included in the answer for when you need to filter more than one result from the array.

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.