问题
I have to find all documents in collection, also those nested, by one field that all of them have (common_field). In xpath it would be something like this: //*[@common_field='value']. How to do something like this in mongo?
{
"_id": ObjectId(
"5e3800700045c500cecffb00"
),
"common_field": "100281",
"other_field": "other",
"A": {
"common_field": "313000000",
"a_field": "a"
},
"B": {
"common_field": "213125",
"b_field": "bb",
"B": {
"common_field": "543534",
"b_field": "b"
},
"C": {
"common_field": "312312",
"c_field": "c"
}
}
}
回答1:
I don't think you can achieve it natively with the Aggregation framework, you have to write a recursive function. This one should work:
var CheckField = function (doc, fieldName, value) {
var ret = false;
Object.keys(doc).forEach(function (key) {
if (key == fieldName && doc[key] == value) {
ret = true;
} else {
if (typeof doc[key] == "object")
ret = ret || CheckField(doc[key], fieldName, value);
}
});
return ret;
};
Then use the function like this:
var ObjIds = []
db.col.find({}).forEach(function (myDoc) {
if (CheckField(myDoc, "common_field", "313000000"))
ObjIds.push(myDoc._id);
})
Either print documents directly of use returned array as query filter:
db.col.find({ _id: { $in: ObjIds } })
来源:https://stackoverflow.com/questions/60038857/mongodb-query-for-nested-elements-on-each-level