使用 MongoD 中的数组值获取特定文档


使用 limi() 以及 toArray() 获取特定的文档。toArray() 方法返回一个数组,其中包含游标中的所有文档。我们创建一个包含文档的集合 -

> db.demo482.insertOne({_id:1,"StudentInformation":[{"Name":"Chris","Age":21}]});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo482.insertOne({_id:2,"StudentInformation":[{"Name":"Bob","Age":23}]});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo482.insertOne({_id:3,"StudentInformation":[{"Name":"David","Age":20}]});
{ "acknowledged" : true, "insertedId" : 3 }

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

> db.demo482.find();

这将产生以下输出 -

{ "_id" : 1, "StudentInformation" : [ { "Name" : "Chris", "Age" : 21 } ] }
{ "_id" : 2, "StudentInformation" : [ { "Name" : "Bob", "Age" : 23 } ] }
{ "_id" : 3, "StudentInformation" : [ { "Name" : "David", "Age" : 20 } ] }

以下是使用 limit() 获取特定文档的查询 -

> db.demo482.find({}).limit(2).toArray();

这将产生以下输出 -

[
   {
      "_id" : 1,
      "StudentInformation" : [
         {
            "Name" : "Chris",
            "Age" : 21
         }
      ]
   },
   {
      "_id" : 2,
      "StudentInformation" : [
         {
            "Name" : "Bob",
            "Age" : 23
         }
      ]
   }
]

更新于:2020 年 5 月 11 日

84 次浏览

开启你的职业生涯

完成课程后获得认证

开始学习
广告
© . All rights reserved.