【发布时间】:2018-04-23 19:43:01
【问题描述】:
我需要修改另一个数组中的数组中的文档。 我知道 MongoDB 不支持多个 '$' 同时迭代多个数组,但他们为此引入了 arrayFilters。 见:https://jira.mongodb.org/browse/SERVER-831
MongoDB的示例代码:
db.coll.update({}, {$set: {“a.$[i].c.$[j].d”: 2}}, {arrayFilters: [{“i.b”: 0}, {“j.d”: 0}]})
Input: {a: [{b: 0, c: [{d: 0}, {d: 1}]}, {b: 1, c: [{d: 0}, {d: 1}]}]}
Output: {a: [{b: 0, c: [{d: 2}, {d: 1}]}, {b: 1, c: [{d: 0}, {d: 1}]}]}
文档的设置方式如下:
{
"_id" : ObjectId("5a05a8b7e0ce3444f8ec5bd7"),
"name" : "support",
"contactTypes" : {
"nonWorkingHours" : [],
"workingHours" : []
},
"workingDays" : [],
"people" : [
{
"enabled" : true,
"level" : "1",
"name" : "Someone",
"_id" : ObjectId("5a05a8c3e0ce3444f8ec5bd8"),
"contacts" : [
{
"_id" : ObjectId("5a05a8dee0ce3444f8ec5bda"),
"retries" : "1",
"priority" : "1",
"type" : "email",
"data" : "some.email@email.com"
}
]
}
],
"__v" : 0
}
这是架构:
const ContactSchema = new Schema({
data: String,
type: String,
priority: String,
retries: String
});
const PersonSchema = new Schema({
name: String,
level: String,
priority: String,
enabled: Boolean,
contacts: [ContactSchema]
});
const GroupSchema = new Schema({
name: String,
people: [PersonSchema],
workingHours: { start: String, end: String },
workingDays: [Number],
contactTypes: { workingHours: [String], nonWorkingHours: [String] }
});
我需要更新联系人。这是我尝试使用 arrayFilters 的方法:
Group.update(
{},
{'$set': {'people.$[i].contacts.$[j].data': 'new data'}},
{arrayFilters: [
{'i._id': mongoose.Types.ObjectId(req.params.personId)},
{'j._id': mongoose.Types.ObjectId(req.params.contactId)}]},
function(err, doc) {
if (err) {
res.status(500).send(err);
}
res.send(doc);
}
);
文档从未更新,我收到以下回复:
{
"ok": 0,
"n": 0,
"nModified": 0
}
我做错了什么?
【问题讨论】:
-
乍一看似乎是正确的。你确定你在
req.params.personId和req.params.contactId中的值是正确的吗?尝试对它们进行硬编码以确保不是问题...另外,您是否尝试过通过另一个客户端运行该查询以确保它不是 Mongoose 问题? -
我发现我使用的是 3.5.12 以下的 MongoDB 版本,它实现了这个 'arrayFilters' 功能。我目前正在设置 3.5.13,我将在此处发布结果。
-
我将 MongoDB 更新到 3.5.13,但仍然无法编辑嵌套文档。得到相同的结果:0, 0, 0
-
如果您打开“调试”
mongoose.set('debug', true),那么您实际上会看到"arrayFilters" is actually being **stripped** from the statement and not being sent to MongoDB at all. I also want to strongly note that MongoDB 3.5 is a **development release** ( so are current 3.6 release candidates ) and as sucharrayFilters` 实际上还没有正式向全世界发布。更新的驱动程序正在为即将发布的实际版本开发。当从与发行版匹配的mongoshell 发出时,该命令运行良好。 -
相关:Mongodb 3.6.0-rc3 array filters not working?。所以它确实工作得很好。只是您正在使用的“已发布”驱动程序实际上并没有赶上允许传递必要的参数。
标签: arrays mongodb mongoose nested