Processing math: 100%

在 MongoDB 嵌套文档中设置条件?


假设我们需要找到一个值大于特定值的文件。要执行此操作,请在嵌套文档中使用点符号,并使用 $gt 设置条件。

我们来看一个示例并创建一个包含文档的集合 -

> db.demo688.insert(
... {
... information:{id:1,details:[
...    {otherDetails:{
...       values:75
...       }
...    }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })
> db.demo688.insert({
... information:
... {
... id:2,
... details:
... [
...    {otherDetails:{
...       values:78
...    }
... }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })

使用 find() 方法从集合中显示所有文档 -

> db.demo688.find();

这将产生以下输出 -

{ "_id" : ObjectId("5ea57986a7e81adc6a0b3965"), "information" : { "id" : 1, "details" : [ { "otherDetails" : { "values" : 75 } } ] } }
{ "_id" : ObjectId("5ea5799ca7e81adc6a0b3966"), "information" : { "id" : 2, "details" : [ { "otherDetails" : { "values" : 78 } } ] } }

以下是访问 MongoDB 嵌套文档的查询 -

> db.demo688.find({"information.details.otherDetails.values":{$gt:75}});

这将产生以下输出 -

{ "_id" : ObjectId("5ea5799ca7e81adc6a0b3966"), "information" : { "id" : 2, "details" : [ { "otherDetails" : { "values" : 78 } } ] } }

更新时间: 2020 年 5 月 14 日

290 次浏览

开启你的 职业

完成课程后获得证书

开始
广告