【问题标题】:How to return only the updated subdocument inside of array after an update [duplicate]更新后如何仅返回数组内的更新子文档[重复]
【发布时间】: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 中进行投影,另一个将向您展示位置运算符如何帮助投影数组元素。

标签: mongodb mongoose


【解决方案1】:

您需要对findOneAndUpdate 函数应用回调

例如:

db.getCollection("users").findOneAndUpdate(
  { "inbox.sent._id": ObjectId("5cea23be8c03c800d43a8376") },
  { "$set": { "inbox.sent.$.inTrash": false } },
  { "inbox.sent.$": 1 },
  function (err, res) {
    //here you have the res, which will be the affected record
  }
);

【讨论】:

  • 我知道你需要提供一个cb,更新返回整个文档和整个inbox.sent数组
  • 不幸的是,没有其他方法可以使用findOneAndUpdate 函数来定位记录的特定区域。您只想要数组的更新部分吗?
猜你喜欢
  • 1970-01-01
  • 2020-08-05
  • 2015-06-03
  • 1970-01-01
  • 2021-04-08
  • 2017-08-22
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
相关资源
最近更新 更多