如何在查找文档时阻止 MongoDB 返回对象 ID?


如要阻止 MongoDB 在查找文档时返回对象 ID,你需要将_id 设为 0。我们先创建一个带有文档的集合

> db.preventObjectIdDemo.insertOne(
...    {
...
...       "StudentName" : "Chris",
...       "StudentDetails" : [
...          {
...             "StudentTotalScore" : 540,
...             "StudentCountryName" : "US"
...          },
...          {
...             "StudentTotalScore" : 489,
...             "StudentCountryName" : "UK"
...          }
...       ]
...    }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca20a9c66324ffac2a7dc63")
}

以下是使用 find() 方法从集合中显示所有文档的查询

> db.preventObjectIdDemo.find().pretty();

这将产生以下输出

{
   "_id" : ObjectId("5ca20a9c66324ffac2a7dc63"),
   "StudentName" : "Chris",
   "StudentDetails" : [
      {
         "StudentTotalScore" : 540,
         "StudentCountryName" : "US"
      },
      {
         "StudentTotalScore" : 489,
         "StudentCountryName" : "UK"
      }
   ]
}

以下是阻止 MongoDB 在查找文档时返回对象 ID 的查询

> db.preventObjectIdDemo.find({ _id: ObjectId("5ca20a9c66324ffac2a7dc63")},
{StudentDetails: { $slice: [0, 1] } ,'_id': 0} ).pretty();

以下是输出,其中看不到 ObjectID

{
   "StudentName" : "Chris",
   "StudentDetails" : [
      {
         "StudentTotalScore" : 540,
         "StudentCountryName" : "US"
      }
   ]
}

更新时间: 30-7 月-2019

511 次浏览

开启你的 职业生涯

完成课程即可获得认证

开始使用
广告
© . All rights reserved.