MongoDB query with nested structure [duplicate]

梦想与她 提交于 2019-12-24 19:19:59

问题


How can I query (in MongoDB) this nested json structure in order to get only the nested object which has the "position" value equal to "currentPosition" value?

{  
    "JobId": "123"
    "currentPosition" : NumberInt(18), 
    "details" : [
        {
            "position": NumberInt(18),
            "fname" : "Alexander", 
            "lname" : "A",
        },
        {
            "position": NumberInt(18),
            "fname" : "Doug", 
            "lname" : "D",
        },
        {
            "position": NumberInt(15),
            "fname" : "Bruce", 
            "lname" : "B",
        },
        {
            "position": NumberInt(10),
            "fname" : "Tom", 
            "lname" : "T",
        }
    ]
}

Currently I am achieveing this by python code: getting the entire document and looping through the details list in order to find object with "position" value equal to "currentPosition" value.

Final output to look like

{  
    "JobId": "123"
    "currentPosition" : NumberInt(18), 
    "details" : [
        {
                "position": NumberInt(18),
                "fname" : "Alexander", 
                "lname" : "A",
            },
            {
                "position": NumberInt(18),
                "fname" : "Doug", 
                "lname" : "D",
            }
    ]
}

回答1:


You will need to use the aggregation framework for this.

details needs to be unwinded so that you can filter out the unnecessary details.

After the $unwind stage you will have 4 documents in the pipeline. In the next stage you then use a $match to filter out the details you care about.

This means that as a result you will get 2 documents with the same JobId and currentPosition, but with different details

https://docs.mongodb.com/manual/reference/operator/aggregation/unwind

db.getCollection("DELETE_ME").aggregate(
    [
        {
            $unwind: {
                path : "$details",
            }
        },
        {
            $match: {
                "$expr": {"$eq": ["$details.position", "$currentPosition"]}
            }
        },
    ]
);

would return

{ 
    "_id" : ObjectId("---"), 
    "JobId" : "123", 
    "currentPosition" : NumberInt(18), 
    "details" : {
        "position" : NumberInt(18), 
        "fname" : "Alexander", 
        "lname" : "A"
    }
}
{ 
    "_id" : ObjectId("---"), 
    "JobId" : "123", 
    "currentPosition" : NumberInt(18), 
    "details" : {
        "position" : NumberInt(18), 
        "fname" : "Doug", 
        "lname" : "D"
    }
}


来源:https://stackoverflow.com/questions/52258741/mongodb-query-with-nested-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!