MongoDB - Check if value exists for a field in a document

独自空忆成欢 提交于 2020-01-03 10:47:14

问题


I have a collection where the document looks like below:

/* 0 */

{
    "_id" : ObjectId("5320b1c723bc746084fa7107"),
    "channels" : [ 
        3, 
        4
    ]
}


/* 1 */

{
    "_id" : ObjectId("5320b1c723bc746084fa7107"),
    "channels" : [ ]
}

I want to form a query such that I want all documents where channels has some value and is not empty.

I tried this:

db.event_copy.find({"channels":{$exists:true}})

But that will still return me the documents with no values in channel.


回答1:


You need the $size operator. To find something with no elements do the following

db.collection.find({ channels: {$size: 0} })

If you know you have a fixed size then do that

db.collection.find({ channels: {$size: 2} })

Otherwise reverse that with $not

db.collection.find({ channels: {$not:{$size: 0}} })

And you can combine with $and:

db.collection.find({ $and: [ 
    { channels: {$not:{$size: 0}} },
    { channels: {$exists: true } }
]})



回答2:


I did it using this :

db.event_copy.find({'channels.0' : {$exists: true}}).count()



回答3:


Check out the size operator here

db.event_copy.find( { channels: { $size: 0 } } );


来源:https://stackoverflow.com/questions/22367335/mongodb-check-if-value-exists-for-a-field-in-a-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!