Organizational Research By

Surprising Reserch Topic

how to find the matched record in mongodb


how to find the matched record in mongodb  using -'java,mongodb,find'

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.mycollection.insert({"person" : [ { "id":1, "details" : { "name" : "Aswini", "Age" : 10 }}, { "id":2, "details" : { "name" : "Mahesh", "Age" : 11}}]})


Then running

    > db.mycollection.findOne({"person.id":1},{"person.details":1,"_id":0})


the result is :

    {
        "person" :
                [
                    {
                        "details" :
                        {
                         "name" : "Aswini",
                         "Age" : 10
                        }
                    },
                    {
                        "details" :
                        {
                         "name" : "Mahesh",
                         "Age" : 11
                        }
                    }
                ]
    }


But I need as follows:

    {
    "person" : [
                {
                "details" : {
                            "name" : "Aswini",
                            "Age" : 10
                        }
                }
            ]
    }


Don't understand where am making mistake. Please need your help. Am using MongoDB, Java
    

asked Oct 6, 2015 by abhi
0 votes
4 views



Related Hot Questions

2 Answers

0 votes

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})
answered Oct 6, 2015 by ashishshukla
0 votes

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})
answered Oct 6, 2015 by rajesh

...