select only subdocuments or arrays

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


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 15:02

    Tried this:

    db.countries.aggregate(      
        {
            "$project": {
                "state": "$states",
                "_id": 0
            }
        },
        {
            "$unwind": "$state"
        },
        {
            "$group": {
                "_id": "$state.name",
                "state": {
                    "$first": "$state"
                }
            }
        },
        {
            "$match": {
                "_id": "orissa"
            }
        }
    );
    

    And got:

    {
        "result" : [
                {
                        "_id" : "orissa",
                        "state" : {
                                "name" : "orissa",
                                "direction" : "east",
                                "population" : 41947358,
                                "districts" : [
                                        {
                                                "name" : "puri",
                                                "headquarter" : "puri",
                                                "population" : 1498604
                                        },
                                        {
                                                "name" : "khordha",
                                                "headquarter" : "bhubaneswar",
                                                "population" : 1874405
                                        }
                                ]
                        }
                }
        ],
        "ok" : 1
    

提交回复
热议问题