如何在查找文档时阻止 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"
}
]
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP