MongoDB 查询以更新嵌套数组

编程入门 行业动态 更新时间:2024-10-22 22:59:50
本文介绍了MongoDB 查询以更新嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在 mongoDB 中使用一些嵌套数组,但是在与 mongo 文档和其他几个 SO 问题争论了几个小时之后.我想我可能做错了什么.下面的代码应该更新 confirms 数组中的 confirms 数组,但它除了添加新条目外不会做任何事情.任何帮助将不胜感激.

I'm trying to use some nested arrays in mongoDB but after several hours fighting with the mongo docs and several other SO questions. I'm thinking I might be doing something terribly wrong. The code below is supposed to update the confirms array in the confirms array but it won't ever do anything but add new entries. Any help would be appreciated.

Events.update({_id: eventId, "confirms.person": personId}, { $set: { "confirms.$.person": personId, "confirms.$.confirmed": isConfirmed, "confirms.$.timestamp": new Date() } });

这是我尝试操作的数据示例,它目前是错误的,因为 personId 应该是唯一的.

And here is a sample of the data I'm trying to operate on, it is currently WRONG because a personId should be unique.

{ "_id": "RnE4PaPSZ9FC9MAAQ", "eventTitle": "Epic lan PARTY!!!!!", "eventDate": "31/07/2015", "confirms": [{ "person": "jjoqekYYaA6n8nYvs", "confirmed": true, "timestamp": ISODate("2015-07-25T17:15:28.212Z") }, { "person": "jjoqekYYaA6n8nYvs", "confirmed": true, "timestamp": ISODate("2015-07-25T17:16:50.485Z") } }] }

以防万一它可能是相关的,我正在使用meteor js.

Just in case it might turn out to be relevant, i'm working in meteor js.

推荐答案

要更新作为集合项的变量的数组的元素,您可以这样做:

To update the element of an array which is the variable of a Collection item you could do this:

  • 获取数组:

  • Get the array:

    var arr = Events.findOne({_id: eventId}).confirms;

    var arr = Events.findOne({_id: eventId}).confirms;

    做你的操作

    用修改后的数组更新旧数组:

    Update old array with modified array:

    Events.update({_id: eventId}, {$set: {confirms: arr}});

    Events.update({_id: eventId}, {$set: {confirms: arr}});

    如果第 2 步出现问题:您可以遍历数组检查是否 this.person === personId 然后设置 this.confirmed = isConfirmed &this.timestamp = 新日期.

    In case of problems with step 2: you could iterate through the array checking if this.person === personId then set this.confirmed = isConfirmed & this.timestamp = new Date.

    在 Mongo 中可能有对数组进行操作的方法,但这个方法肯定有效.

    There might be ways of operating on arrays within Mongo but this one works for sure.

  • 更多推荐

    MongoDB 查询以更新嵌套数组

    本文发布于:2023-11-22 20:43:59,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1618953.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:嵌套   数组   MongoDB

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!