Is there a way to prevent cuff requests for arrays?

If I have the following documents:

{a: {x:1}} // without array {a: [{x:1}]} // with array 

Is there a query method for {'a.x':1} that will return the first but not the second? IE, I need a document where ax is 1 and a is not an array.

+5
source share
2 answers

Note that a future version of MongoDB will include the expression $isArray aggregation . Meanwhile...

... the following code will do the trick, since the $elemMatch only matches documents that have an array field:

 > db.test.find({"ax": 1, "a": {$not: {$elemMatch: {x:1}}}}) 

Given this dataset:

 > db.test.find({},{_id:0}) { "a" : { "x" : 1 } } { "a" : [ { "x" : 1 } ] } { "a" : [ { "x" : 0 }, { "x" : 1 } ] 

He will return:

 > db.test.find({"ax": 1, "a": {$not: {$elemMatch: {x:1}}}}, {_id:0}) { "a" : { "x" : 1 } } 

Please note that this should be considered as a short-term solution. The MongoDB team made sure that [{x:1}] and {x:1} behave the same way (see dot-notation or $type for arrays ). Therefore, you should think that at some point in the future $elemMatch may be updated (see Question JIRA SERVER-6050 ). In the meantime, it might be worth considering fixing your data model, so you would no longer need to distinguish between an array containing one subdocument and a bare subdocument.

+5
source

You can do this by adding a second term that ensures that a has no elements. This second member will always be true if a is a simple pallet and always false when a is an array (since otherwise the first member would not match).

 db.test.find({'a.x': 1, 'a.0': {$exists: false}}) 
+5
source

All Articles