gpt4 book ai didi

java - 为什么我收到的文档未包含在投影中?

转载 作者:行者123 更新时间:2023-11-30 07:24:24 25 4
gpt4 key购买 nike

我的 Collection 中有这 2 个文档:

{ 
"_id" : ObjectId("5722042f8648ba1d04c65dad"),
"companyId" : ObjectId("570269639caabe24e4e4043e"),
"applicationId" : ObjectId("5710e3994df37620e84808a8"),
"steps" : [
{
"id" : NumberLong(0),
"responsiveUser" : "57206f9362d0260fd0af59b6",
"stepOnRejection" : NumberLong(0),
"notification" : "test"
},
{
"id" : NumberLong(1),
"responsiveUser" : "57206fd562d0261034075f70",
"stepOnRejection" : NumberLong(1),
"notification" : "test1"
}
]
}
{
"_id" : ObjectId("5728f317a8f9ba14187b84f8"),
"companyId" : ObjectId("570269639caabe24e4e4043e"),
"applicationId" : ObjectId("5710e3994df37620e84808a8"),
"steps" : [
{
"id" : NumberLong(0),
"responsiveUser" : "57206f9362d0260fd0af59b6",
"stepOnRejection" : NumberLong(0),
"notification" : "erter"
},
{
"id" : NumberLong(1),
"responsiveUser" : "57206f9362d0260fd0af59b6",
"stepOnRejection" : NumberLong(1),
"notification" : "3232"
}
]
}

现在我正在尝试获取 ma​​x _idid 等于 0 的文档来自 steps 数组内的文档。我还有一个投影,它应该显示匹配元素的id,而不显示其他内容。

这是我的查询:

collection
.find(new Document("companyId", companyId)
.append("applicationId", applicationId)
.append("steps",
new Document("$elemMatch",
new Document("id", 0))))
.sort(new Document("_id", 1))
.limit(1)
.projection(new Document("steps.id", 1)
.append("_id", 0));

它返回:

Document{{steps=[Document{{id=0}}, Document{{id=1}}]}}

为什么它返回 2 个文档而不是 1 个?

结果应该是这样的:

Document{{id=0}}

我在这里缺少什么?我知道这是基本的事情,但我真的无法在这里发现我的错误。

最佳答案

您的查询文档告诉 Mongo 返回那些在“steps”数组中具有 id: 0 的文档的文档。您没有告诉 Mongo 仅返回该字段。您可以在投影文档中使用 $elemMatch 来获取您想要的内容(我使用 Mongo shell 语法编写此内容,因为我对 Java 语法不太熟悉):

{   steps: { $elemMatch: { id: 0 } }, 
'steps.id': 1,
_id: 0
}

关于java - 为什么我收到的文档未包含在投影中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37003401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com