问题
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