简体   繁体   English

MongoDB - 检查文档中某个字段的值是否存在

[英]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.

相关问题 检查MongoDB中是否存在具有字段值的文档的最佳做法是什么? - What is the best practice to check if document with field value exists in MongoDB? 检查mongodb中的数组字段中是否存在值 - check if value exists in array field in mongodb 如何在进行聚合时检查 mongodb object 中是否存在键,其中键是文档中某个其他字段的值? - How to check if a key exists in a mongodb object where the key is a value of some another field in the document while doing aggregation? 使用 MongoDB 检查字段是否存在 - Check that Field Exists with MongoDB 检查条件是否存在Mongodb Document中字段的Python方法 - Pythonic way to check if field in Mongodb Document exists on a conditional 检查之前是否已经存在字段以在 MongoDB / NodeJS 上创建文档 - check if already exists field before to create a document on MongoDB / NodeJS Mongodb 检查数组的子文档中是否存在字段 - Mongodb check If field exists in an sub-document of an array 如何使用C#检查特定文档Mongodb中是否存在字段? - how to check if a field exists in a specific document Mongodb using C#? 如何检查字段是否存在,如果存在,在 mongodb $in 中获取其值? - How to check if the field exists and if exists, get its value in mongodb $in? MongoDB检查文档/记录是否存在 - MongoDB Check if a document/record exists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM