I need to find all Documents and Sub-Documents which contain a particular field, eg the field staffNumber
might be a field in a employees
collections Document as well as in a managers
-Collections Sub-Documents. I want to search all Documents of all types for staffNumber
fields without knowing which collection contains possible matches.
So let's setup some test data to start with:
> 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 })
>
Then we can use the $where operator to run a bit of 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");
} } );
This will then yeild the following results:
{ "_id" : ObjectId("5a9d4146be02da4d3fc1940a"), "test" : true, "staffNumber" : 1234 }
{ "_id" : ObjectId("5a9d4153be02da4d3fc1940b"), "test" : true, "other" : { "staffNumber" : 1234 } }
{ "_id" : ObjectId("5a9d4166be02da4d3fc1940c"), "test" : true, "other1" : { "other2" : { "staffNumber" : 1234 } } }
More reading on $where
- https://docs.mongodb.com/manual/reference/operator/query/where/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.