如何在 MongoDb 集合中找到文档或其子文档的属性包含空对象值 {}
的所有文档?
属性(property)名称未知。
应返回哪些文件的示例:
{
data: {
comment: {}
}
}
如data
和comment
所述,属性名称未知。
最佳答案
在聚合管道中迭代对象属性的方法是$objectToArray运算符,它将文档转换为键值对数组。不幸的是,它不会展平嵌入的文档。在实现此类支持之前,我看不到使用纯聚合管道完成任务的方法。
但是你总是可以使用 $where运算符并将逻辑放入 JavaScript 代码中。它应该递归地遍历所有文档属性并检查该值是否为空文档。这是一个工作示例:
db.collection.find({"$where" : function () {
function hasEmptyProperties(doc) {
for (var property in doc) {
var value = doc[property];
if (value !== null && value.constructor === Object &&
(Object.keys(value).length === 0 || hasEmptyProperties(value))) {
return true;
}
}
return false;
}
return hasEmptyProperties(this);
}});
如果您使用以下数据填充集合:
db.collection.insert({ _id: 1, p: false });
db.collection.insert({ _id: 2, p: [] });
db.collection.insert({ _id: 3, p: null });
db.collection.insert({ _id: 4, p: new Date() });
db.collection.insert({ _id: 5, p: {} });
db.collection.insert({ _id: 6, nestedDocument: { p: "Some Value" } });
db.collection.insert({ _id: 7, nestedDocument: { p1: 1, p2: {} } });
db.collection.insert({ _id: 8, nestedDocument: { deepDocument: { p: 1 } } });
db.collection.insert({ _id: 9, nestedDocument: { deepDocument: { p: {} } } });
查询将正确检测所有具有空属性的文档:
{ "_id" : 5, "p" : { } }
{ "_id" : 7, "nestedDocument" : { "p1" : 1, "p2" : { } } }
{ "_id" : 9, "nestedDocument" : { "deepDocument" : { "p" : { } } } }
仅供引用,这是一个基于 $objectToArray
的聚合管道,它检测空属性,但不在嵌套文档中:
db.collection.aggregate(
[
{ "$project": {
_id: 1,
"properties": { "$objectToArray": "$$ROOT" }
}},
{ "$project": {
_id: 1,
propertyIsEmpty: {
$map: {
input: "$properties.v",
as: "value",
in: { $eq: ["$$value", {} ] }
}
}
}},
{ "$project": {
_id: 1,
anyPropertyIsEmpty: { $anyElementTrue: [ "$propertyIsEmpty" ] }
}},
{$match : {"anyPropertyIsEmpty" : true}},
{ "$project": {
_id: 1,
}},
]);
关于mongodb - 在 MongoDb 集合中查找空对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49513019/