开发者

In Mongo, how do I determine how deeply nested an object is?

I am using MongoDB to store an object which contains a sub-object which [normally] just contains name/value pairs of strings. We are seeing some data corruption where the objects are becoming more deeply nested than they should.

For example, this is a valid object:

{ "_id" : 1, "d": { "a":"foo", "b":"bar" } }

We are seeing some invalid objects, like the following:

{ "_id" : 1, "d": { "a":"foo", "b":{ "c":"bar" } } }

or:

{ "_id" : 1, "d": { "a":{ "z":"foo" }, "b":"bar" } }

I would like to write a query to find all corrupted values. Anything where a value in the 'd' property is an object instead of a strin开发者_运维百科g.


db.foo.find(function() { for (f in this) { var v = this[f]; if (typeof v == "object" && !(v instanceof Array) && !(v instanceof ObjectId) && !(v instanceof NumberLong) && !(v instanceof Date) && !(v instanceof BinData)) return true; } return false; })

Type checking is ugly, can it be done better?


Seems you need just check type of 'b' property:

// matches if 'b' is a string - valid objects
db.things.find( { "d.b" : { $type : 2 } } ); 

 // matches if 'b' is a object - invalid objects
db.things.find( { "d.b" : { $type : 3 } } );

Documentation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜