0

I have collection like this:

{
    "name":"silver",
    mywants:[
    {"_id":objid(545454ddfdf5),mark:{"english":100,"math":100,"science":100}},
    {"_id":objid(5878784dfd5d),mark:{"english":100,"math":100,"science":100}},
    {"_id":objid(5454dfd44545),mark:{"english":100,"math":100,"science":100}},
    {"_id":objid(541dfee88245),mark:{"english":100,"math":100,"science":100}},
    ]
}

I want to find that given objid is exist in mywants array or not. Then if exist that objid i want that exist object id document to my callback function so i have tried like this

collection.find("{"name":"silver"},{"mywants._id":objid}).toArray(function(err,res)
{
    console.log(JSON.stringify(res));
})

But, I got output like 

[{"Mywant":[{"_id":"5128b9bc046802720b000003"},
    {"_id":"5128c190046802720b000004"},
    {"_id":"5128c359175e1aa80b000001"}],"_id":"5128b71455e4e0540b000002"}
]

But i want like this

{"_id":objid(545454ddfdf5),mark:{"english":100,"math":100,"science":100}}`,

How to find?

2 Answers 2

1

You have to call

collection.find({"name":"silver", "mywants._id":objid}).toArray(…)

instead of

collection.find({"name":"silver"},{"mywants._id":objid}).toArray(…)

. The former one represents a query with two expressions ("name":"silver" AND "mywants._id":objid) while the latter one is one expression ("name":"silver") and one projection ("mywants._id":objid) [controls the fields to return]. More info at http://docs.mongodb.org/manual/reference/method/db.collection.find/.

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

2 Comments

if i use like above i got this error SyntaxError: Unexpected token {
I edited my answer and omitted the inner braces, please check if it is working now.
0

You have typo in your code, it is not ver clear what youwant. Based on your sample with typo and output you want (again with typo) I assume this is what you meant:

-You are doing a find on name:"silver" and want back mywants._id field (has typo) with that syntax.

Instead I assume you meant to find:

name:"silver" AND "mywants._id" : someSpecificId

and output corresponding mywants entry:

db.collection.find({"name":"silver","mywants._id":objid}, {"mywants.$":1, _id:0}).pretty()

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.