Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 如何在更新后仅返回数组内部更新的子文档_Mongodb_Mongoose - Fatal编程技术网

Mongodb 如何在更新后仅返回数组内部更新的子文档

Mongodb 如何在更新后仅返回数组内部更新的子文档,mongodb,mongoose,Mongodb,Mongoose,我有一个具有以下模式的用户模型 { _id: userId, inbox: { inbox: [Array of message documents], sent: [Array of message documents], } } 有没有办法在mongodb/mongoose中更新后只获取更新的子文档 更新很好,我只想返回更新的子文档,而不是再次查询数据库 db.getCollection("users").findOneAndUpdate( { "inbox

我有一个具有以下模式的用户模型

{
  _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
);

您需要对
findOneAndUpdate
函数应用回调

e、 g:


您需要对
findOneAndUpdate
函数应用回调

e、 g:


您的模式是什么样子的?更新后您希望得到什么样的预期输出?@Fanpark我知道您可以选择字段,但因为它是一个数组,所以我将获得完整长度的数组,并且我需要对其进行迭代以找到子文档。有没有一种方法可以获得一个包含单个元素的数组,比如我们使用
db.getCollection(“users”).findOne({“inbox.sent.\u id”:ObjectId(“5cea23be8c03c800d43a8376”)}、{“inbox.sent.$”:1})
请检查两个重复的答案。其中一个将解释如何在findOneAndUpdate中进行投影,另一个将向您展示位置运算符如何帮助投影数组元素。您的模式是什么样的?更新后您希望得到什么样的预期输出?@Fanpark我知道您可以选择字段,但因为它是一个数组,所以我将获得完整长度的数组,并且我需要对其进行迭代以找到子文档。有没有一种方法可以获得一个包含单个元素的数组,比如我们使用
db.getCollection(“users”).findOne({“inbox.sent.\u id”:ObjectId(“5cea23be8c03c800d43a8376”)}、{“inbox.sent.$”:1})
请检查两个重复的答案。一个将解释如何在findOneAndUpdate中进行投影,另一个将向您展示位置运算符如何帮助投影数组元素。我知道您需要提供一个
cb
,更新将返回包含整个
收件箱的整个文档。已发送
arrayun幸运的是,使用
findOneAndUpdate
函数无法以记录的特定区域为目标。您只需要数组的更新部分吗?我知道您需要提供一个
cb
,更新将返回整个
收件箱中的整个文档。发送
arrayun幸运的是,
findOneAndUpdate
函数没有其他方法可以针对记录的特定区域。是否只需要阵列的更新部分?
{
  _id: userId,
  inbox: {
    sent: [{ updated doc}]
  }  
}
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
  }
);