如何防止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"
}
]
}