我需要找到包含特定字段的所有文档和子文档,例如,该字段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] 删除。
我来说两句