How to Find the matched record in mongodb?

前端 未结 2 490
一个人的身影
一个人的身影 2021-01-13 10:06

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         


        
相关标签:
2条回答
  • 2021-01-13 10:45

    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})
    
    0 讨论(0)
  • 2021-01-13 11:03

    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})
    
    0 讨论(0)
提交回复
热议问题