MongoDB 查询以更新嵌套数组 [英] MongoDB query to update nested array

查看:41
本文介绍了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:

  1. 获取数组:

  1. 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 查询以更新嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆