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

问题描述 投票:1回答:1

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

mongodb
1个回答
0
投票

所以我们先设置一些测试数据:

> 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 } } }

更多关于$where的读物 - https://docs.mongodb.com/manual/reference/operator/query/where/

© www.soinside.com 2019 - 2024. All rights reserved.