select only subdocuments or arrays

后端 未结 5 706
情书的邮戳
情书的邮戳 2021-02-06 14:59
{
    \"_id\":{
        \"oid\":\"4f33bf69873dbc73a7d21dc3\"
    },
    \"country\":\"IND\",
    \"states\":[{
            \"name\":\"orissa\",
            \"direction\"         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-06 15:08

    Any query in mongodb always return root document.

    There is only one way for you to load one sub document with parent via $slice if you know ordinal number of state in nested array:

    // skip ordinalNumberOfState -1, limit 1
    db.countries.find({_id: 1}, {states:{$slice: [ordinalNumber -1 , 1]}}) 
    

    $slice work in default order (as documents was inserted in nested array). Also if you don't need fields from a country you can include only _id and states in result:

    db.countries.find({_id: 1}, {states:{$slice: [ordinalNumber -1 , 1]}, _id: 1}) 
    

    Then result document will looks like this one:

    {
        "_id":{
            "oid":"4f33bf69873dbc73a7d21dc3"
        },
        "states":[{
                "name":"orissa",
                "direction":"east",
                "population":41947358,
                "districts":[{
                        "name":"puri",
                        "headquarter":"puri",
                        "population":1498604
                    },
                    {
                        "name":"khordha",
                        "headquarter":"bhubaneswar",
                        "population":1874405
                    }
                ]
            }]
    }
    

提交回复
热议问题