[英]MongoDB - Check if value exists for a field in a document
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.但这仍然会返回通道中没有值的文档。
You need the $size operator.您需要$size运算符。 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否则用$not反转它
db.collection.find({ channels: {$not:{$size: 0}} })
And you can combine with $and :你可以结合$and :
db.collection.find({ $and: [
{ channels: {$not:{$size: 0}} },
{ channels: {$exists: true } }
]})
我是用这个做的:
db.event_copy.find({'channels.0' : {$exists: true}}).count()
在此处查看尺寸运算符
db.event_copy.find( { channels: { $size: 0 } } );
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['my_database']
col=db['my_collection']
### Input
email="test@gmail.com"
########
exist_count=col.find({"email": email},{'_id':0}).count()
if exist_count>=1:
print("Field value is present")
else:
print("Field value is not present")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.