I have this json file:
{
"id" : 100,
"boolean": 1,
"color": 2,
"MYtable": [{"a":1, "b":2}],
"number": 4,
"string": 5
}
{
"id" : 200,
"boolean": 1,
"color": 22,
"MYtable": [{"a":10, "b":20,"c":30}],
"number": 42,
"string": 52
}
{
"id" : 300,
"boolean": 13,
"color": 223,
"MYtable": [],
"number": 423,
"string": 523
}
Using a mongodb query I would like to get only the elements that have MYtable of size 1 or larger. For example in the above json I would only get the elements with id 100 and 200.
MYcollection is my database's collection.
I tried this:
MYcollection.find({ "MYtable": {"$size": {"$gt" :1}}})
and also this:
MYcollection.find({"$where" : "this.MYtable.length > 1"})
But it didn't work. What am I missing?
You can use $expr
with $size
to filter the documents
db.col.find({$expr : {$gt : [{$size : "$MYtable"},1]}})
try using $expr
, below from the documentation
$expr is faster than $where because it does not execute JavaScript and should be preferred where possible.
EDIT -1
you may need to change your document structure to store the array elements
the below works with you document structure by converting the array element at 0 to an array to compare the size
db.col.find({$expr:{$gt:[{$size:{$ifNull:[{"$objectToArray":{$arrayElemAt:[{$ifNull:["$MYtable",[]]},0]}},[]]}},1]}})
There is a imho hacky but often seen way:
db.collection.find({'yourArrayField.1' : {$exists : true}}
I am not sure currently, if there can be undefined fields between existing ones, but it is a simple solution that might work for you.
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.