所以我试图找到所有具有字段集且不为空的记录。
我尝试使用 $exists
,但是根据 MongoDB documentation,,此查询将返回等于 null 的字段。
$exists 确实匹配包含存储空值的字段的文档。
所以我现在假设我必须做这样的事情:
db.collection.find({ "fieldToCheck" : { $exists : true, $not : null } })
但是,每当我尝试此操作时,我都会收到错误 [invalid use of $not]
有人知道如何查询这个吗?
使用 $ne
(表示“不等于”)
db.collection.find({ "fieldToCheck": { $ne: null } })
假设我们有一个如下的集合:
{
"_id":"1234"
"open":"Yes"
"things":{
"paper":1234
"bottle":"Available"
"bottle_count":40
}
}
我们想知道瓶子字段是否存在?
答:
db.products.find({"things.bottle":{"$exists":true}})
When <boolean> is true, $exists matches the documents that contain the field, including documents where the field value is null.
From the docs.
我发现这对我有用
db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})
db.<COLLECTION NAME>.find({ "<FIELD NAME>": { $exists: true, $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,但是 - 性能将大大提高。
$exists
具有完整索引的当前限制及其原因。
我尝试将其转换为布尔条件,如果具有表名的文档已经存在,那么它将附加到同一个文档中,否则它将创建一个。
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
}
}
}
])
不定期副业成功案例分享
find
始终返回的内容:记录的集合,符合条件。{$exists: true}
是多余的,只需{$ne: null}
就足够了。