【发布时间】:2019-05-26 20:29:59
【问题描述】:
我有一个具有以下架构的用户模型
{
_id: userId,
inbox: {
inbox: [Array of message documents],
sent: [Array of message documents],
}
}
有没有办法在 mongodb / mongoose 更新后只获取更新的子文档?
更新很好,我只想返回更新后的子文档,而不是再次查询数据库
db.getCollection("users").findOneAndUpdate(
{ "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") },
{ "$set": { "inbox.sent.$.inTrash": false } },
{ "inbox.sent.$": 1 } <-- how to return only the subdocument like in a query
);
预期在 inbox.sent 输出数组,仅包含更新的文档
{
_id: userId,
inbox: {
sent: [{ updated doc}]
}
}
【问题讨论】:
-
您的架构是什么样的?更新后您想要什么预期输出?
-
@Fanpark 我知道你可以选择字段,但是因为它是一个数组,所以我会得到全长数组,我需要遍历它来找到子文档。有没有办法像我们
db.getCollection("users").findOne( { "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") }, { "inbox.sent.$": 1 } )那样获得一个包含单个元素的数组 -
请检查两个重复的答案。一个将解释您如何在 findOneAndUpdate 中进行投影,另一个将向您展示位置运算符如何帮助投影数组元素。