Reputation: 1457
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?
Upvotes: 0
Views: 276
Reputation: 23797
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()
Upvotes: 0
Reputation: 4975
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/.
Upvotes: 1