所以我试图找到所有具有字段集且不为空的记录。
我尝试使用$exists,但是根据MongoDB 文档,此查询将返回等于 null 的字段。
$exists匹配包含存储空值的字段的文档。
所以我现在假设我必须做这样的事情:
db.collection.find({ "fieldToCheck" : { $exists : true, $not : null } })
然而,每当我尝试这个时,我都会收到错误[invalid use of $not] 任何人都知道如何查询这个?
所以我试图找到所有具有字段集且不为空的记录。
我尝试使用$exists,但是根据MongoDB 文档,此查询将返回等于 null 的字段。
$exists匹配包含存储空值的字段的文档。
所以我现在假设我必须做这样的事情:
db.collection.find({ "fieldToCheck" : { $exists : true, $not : null } })
然而,每当我尝试这个时,我都会收到错误[invalid use of $not] 任何人都知道如何查询这个?
使用$ne(用于“不等于”)
db.collection.find({ "fieldToCheck": { $exists: true, $ne: null } })
假设我们有一个如下的集合:
{
"_id":"1234"
"open":"Yes"
"things":{
"paper":1234
"bottle":"Available"
"bottle_count":40
}
}
我们想知道瓶子字段是否存在?
答:
db.products.find({"things.bottle":{"$exists":true}})
我发现这对我有用
db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})
本注释写于2021 年,适用于 MongoDB 5.X 及更早版本。
如果您重视查询性能,则 永远不要使用 $exists(或仅在查询的字段上有稀疏索引时才使用它。稀疏索引应与查询的条件匹配,这意味着,如果搜索 $exists:true,则稀疏索引应该在field:{$exist:true}上,如果你正在查询$exists:true稀疏索引应该在field:{$exist:false}上
而是使用:
db.collection.find({ "fieldToCheck": { $ne: null } })
或者
db.collection.find({ "fieldToCheck": { $eq: null } })
这将要求您在集合的每个文档中包含 fieldToCheck,但是 - 性能将大大提高。
db.<COLLECTION NAME>.find({ "<FIELD NAME>": { $exists: true, $ne: null } })
我尝试将其转换为布尔条件,如果具有表名的文档已经存在,那么它将附加到同一个文档中,否则它将创建一个。
table_name 是我试图用来查找文档的变量
query = { table_name : {"$exists": "True"}}
result = collection.find(query)
flag = 0
for doc in result:
collection.update_one({}, { "$push" : { table_name : {'name':'hello'} } } )
flag = 1
if (flag == 0):
collection.insert_one({ table_name : {'roll no' : '20'}})
聚合示例
https://mongoplayground.net/p/edbKil4Zvwc
db.collection.aggregate([
{
"$match": {
"finishedAt": {
"$exists": true
}
}
},
{
"$unwind": "$tags"
},
{
"$match": {
"$or": [
{
"tags.name": "Singapore"
},
{
"tags.name": "ABC"
}
]
}
},
{
"$group": {
"_id": null,
"count": {
"$sum": 1
}
}
}
])