如何防止MongoDB在查找文档时返回对象ID? [英] How to prevent MongoDB from returning the object ID when finding a document?
问题描述
我在 MongoDB 中有以下文档...
I've the following document in MongoDB...
{
"_id" : ObjectId("531221cd960100960116b992"),
"username : "joe",
"address" : [
{
"zip" : "8000",
"city" : "Zurich"
},
{
"zip" : "6900",
"city" : "Lugano"
}
]
}
... 并检索第二个地址,我使用以下语句:
... and to retrieve the second address I use the following statement:
db.users.find({ _id: ObjectId("531221cd960100960116b992") }, { addresses: { $slice: [0, 1] } } )
除了返回对象 id 外,这有效:
This works except it also returns the object id:
{ "addresses" : [ { "zip" : "6900", "city" : "Lugano" } ], "_id" : ObjectId("531221cd960100960116b992") }
如何防止 MongoDB 返回对象 ID?我知道我应该提供一个像 _id : 0
这样的投影......但是我应该把它放在上面的表达式中的什么位置?我做了很多尝试……但都没有成功.
How do I prevent MongoDB from returning the object id? I know I should provide a projection like _id : 0
... but where should I put it in the expression above? I did a number of tries... but without success.
谢谢.
推荐答案
这与@hanleyhansen 的答案完全相同,但只是为了让您知道您可以将 0 与 false 互换使用,例如:
This is exactly the same as @hanleyhansen's answer, but just to let you know that you can use 0 interchangeably with false like:
db.users.find(
{ _id: ObjectId("531221cd960100960116b992")},
{ addresses: { $slice: [0, 1] } ,'_id': 0}
)
这篇关于如何防止MongoDB在查找文档时返回对象ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!