I have a record in my collection and I want to fetch the details of the person whose id is 1. But I am getting the details for 2times instead of 1.
db.m
person
is an array. If you want to get first element of this array you should use $slice
db.mycollection.findOne({"person.id":1},{"person":{$slice:[0,1]},"_id":0})
This is the behavior of filtering multi level embedded document, normally the matching filter would return the whole document, not the subsets.
Usually positional operator $
used to match the sub documents in updates
. But the feature is not yet implemented in return specifiers.
There is an outstanding issue already in mongo Support for positional ($) operator in fields to return specifier. (Please login to vote if you really needed the feature)
So you have to redesgin your schema to handle this, may be like this
db.test.insert({"person" : [ { "id":1, "details" : { "name" : "Aswini", "Age" : 10 }}]})
db.test.insert({"person" : [ { "id":2, "details" : { "name" : "Mahesh", "Age" : 11}}]})
db.test.find({"person.id":1},{'person.details':1})