MongoDb:查找具有特定字段的所有集合中的所有(子)文档

亚历山大·泽特勒

我需要找到包含特定字段的所有文档和子文档,例如,该字段staffNumber可能是employees集合文档以及managers-Collections子文档中的一个字段我想搜索所有类型的所有文档以查找staffNumber字段,而不知道哪个集合包含可能的匹配项。

凯文·史密斯

因此,让我们设置一些测试数据以开始:

> db.test.drop()
true
> db.test.insert({test:true})
WriteResult({ "nInserted" : 1 })
> db.test.insert({test:true, staffNumber: 1234})
WriteResult({ "nInserted" : 1 })
> db.test.insert({test:true, other: {staffNumber: 1234}})
WriteResult({ "nInserted" : 1 })
> db.test.insert({test:true, other1: { other2: {staffNumber: 1234}}})
WriteResult({ "nInserted" : 1 })
>

然后,我们可以使用$ where运算符运行一些javascript:

db.test.find( { $where: function() {
   function hasProp(obj, prop) {
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            if (p === prop && obj[p] !== "" && obj[p] !== undefined && obj[p] !== null) {
                return obj;
            } else if (obj[p] instanceof Object && hasProp(obj[p], prop)) {
                return obj[p];
            }
        }
    }
    return null;
   }
   return hasProp(this, "staffNumber");
} } );

然后,将得出以下结果:

{ "_id" : ObjectId("5a9d4146be02da4d3fc1940a"), "test" : true, "staffNumber" : 1234 }
{ "_id" : ObjectId("5a9d4153be02da4d3fc1940b"), "test" : true, "other" : { "staffNumber" : 1234 } }
{ "_id" : ObjectId("5a9d4166be02da4d3fc1940c"), "test" : true, "other1" : { "other2" : { "staffNumber" : 1234 } } }

有关更多信息-https $where: //docs.mongodb.com/manual/reference/operator/query/where/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在mongodb中查找具有特定字段的所有集合

猫鼬:查找具有特定字段的所有文档

在现有集合(mongodb)的所有文档中添加字段?

在集合的所有文档中添加字段-MongoDB

如何在字段中查找所有具有特定字符串的文档?(Elasticsearch)

如何在Elasticsearch中查找具有特定字段的所有文档?

使用mongoDB中的聚合为集合中的所有文档删除特定字段

mongodb查找子文档的所有值

在pyMongo中查找文档的所有字段

如何在MongoDB集合中的所有子文档上有条件地设置新字段

在mongodb中查找包含任何子字段的所有记录

返回集合中的所有字段 MongoDB

查找mongodb中的所有文档

使用 MongoDB 查找具有不同值的字段的所有文档

查找所有子文档都符合条件的 MongoDB 文档

如何查找具有特定案头的所有文档

如何从集合中的所有文档中删除特定的子文档?

如何使用MongoDb .net驱动程序获取集合中所有文档的几个特定字段

使用MongoDB聚合删除集合中所有文档的特定字段

查找集合中具有给定属性的所有对象

如何在嵌入列表中查找具有匹配字段的所有文档

如何在mongodb中的所有文档中的子文档数组中添加字段?

firestore 从集合中的所有文档中获取字段

在MongoDB中查找子文档中的两个条件都为真的所有文档

如何在具有 2 个值的字段的 mongodb 集合中查找文档?

使用mongo go driver查找集合中的所有文档

更新文档并创建一个字段,该字段是集合MongoDB中具有相同ID的所有对象的数组

从集合中的所有/多个文档中删除嵌套字段 - NodeJS + MongoDB

查询在 MongoDb 集合中的所有文档中创建一个新字段