向mongodb查询字段设置为null的文档,但排除不包含该字段的文档

问题描述 投票:0回答:3

我目前正在尝试使用mongodb mongoshell。

我想获取的文件Tomato.consensus的值为空。以下查询与1991文档匹配。

    db.movieDetails.find({"tomato.consensus": null}

但是不希望的副作用之一是,它还会返回没有tomato.concensus字段和根本没有tomato字段的文档。

我的想法是使用$ exists运算符。该查询返回362个文档。

    db.movieDetails.find({"tomato.consensus": {$exists: true})

我最初的想法是使用field Tomato.consensus获取文档,然后对其进行处理以使用“ tomato.consensus”提取文档:null。 (无效):

    $db.movieDetails.find({"tomato.consensus": {$exists: true}}).find({"tomato.consensus": null})
    $uncaught exception: TypeError: db.movieDetails.find(...).find is not a function :

是否有一种语法可以同时执行这些操作以消除mongo shell中的副作用?

database mongodb nosql mongo-shell
3个回答
1
投票
db.movieDetails.find( { $and: [ { "tomato.consensus": null }, { "tomato.consensus": { $exists: true } } ] } )

1
投票
db.movieDetails.find( { $and: [ {"tomato.consensus": { $exists: true } }, {"tomato.consensus": null } ] } )

查找有关$ and运算符和示例here的更多详细信息。


0
投票
检查undefined可以通过某些方式完成:

1){"tomato.consensus": { $exists: false } }

2){"tomato.consensus": undefined }

因此,为了搜索空值但不是未定义的,请使用查询:

{'tomato.consensus': null, 'tomato.consensus': { $exists : true }}

© www.soinside.com 2019 - 2024. All rights reserved.