mongodb - 在 MongoDb 集合中查找空对象属性

标签 mongodb

如何在 MongoDb 集合中找到文档或其子文档的属性包含空对象值 {} 的所有文档? 属性(property)名称未知。

应返回哪些文件的示例:

{
  data: {
      comment: {}
  }
}

datacomment所述,属性名称未知。

最佳答案

在聚合管道中迭代对象属性的方法是$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/

相关文章:

node.js - MongoDB + NodeJS + Express - 用户可以向已经是他们 friend 的人发送好友请求

python - 使用 Ming 连接到 MongoDB 副本集

Ruby 检查 mongodb 中是否存在记录

java - 使用java在mongodb中自动递增序列

java - 如何在没有注释的情况下在 Spring 核心中初始化 MongoClient 时注入(inject) Mongo 选项?

javascript - Collection.find() 仅适用于某些集合

java - MongoDB 和 Spring MVC : PATCH operation?

node.js - Mongoose 辅助方法没有 findOne 方法?

ruby-on-rails - Mongoid `group()` 条件

ruby-on-rails - Mongoid:搜索数组