Node.js 阵列过滤器不工作的mongoDB更新
我在mongo中有以下文档结构(简化):Node.js 阵列过滤器不工作的mongoDB更新,node.js,mongodb,Node.js,Mongodb,我在mongo中有以下文档结构(简化): { "_id":"5e30208675b5400cb0894c52", "locations": [ { "name": "Pleasure Gardens", "id": 618, "areas": [ { "name
{
"_id":"5e30208675b5400cb0894c52",
"locations": [
{
"name": "Pleasure Gardens",
"id": 618,
"areas": [
{
"name": "Koi Pond",
"area_id": 159,
"is_active": true,
},
...other areas
],
...other locations
}
]
}
我试图将区域数组中的is_active字段设置为false,其中位置的id为618,区域的区域id为159
我正在做以下工作:
const db = await connectDb();
return await db
.collection('test')
.updateOne(
{"locations.areas.area_id": 159},
{ $set: {"locations.$[l].areas.$[a].is_active": false }},
{ arrayFilters: [{ "l.id": 618 }, { "a.area_id": 159 }] }
);
但我得到了:
MongoError: cannot use the part (locations of locations.$[l].areas.$[a].is_active) to traverse the element
我已经检查了其他回复,就我所知,语法是正确的,我还使用了一个mongodb版本,它支持nodejs中的arrayFilters方法(“mongodb”:“^3.6.3”),那么为什么对我如此残忍呢?为什么
更新
在阅读了这些评论之后,我意识到尽管我已经安装了mongodb npm包的3.6.3版本,但数据库本身的版本实际上是3.0.14
这意味着不支持arrayFilters方法,我可能需要采取两步方法来解决此问题:
- 将结果存储在变量中
- 使用更新代码本身中的变量(更改为false)
For me工作正常(mongod/mongos版本4.4.3): }
For me工作正常(mongod/mongos版本4.4.3): }
伙计,这不能解决问题,也许我失踪了something@Minsky:成功的测试详细信息很难作为评论发布,因此作为答案发布。。。(只是试图帮助陷入困境的人…)伙计,这并不能解决问题,也许我失踪了something@Minsky:成功的测试详细信息很难作为评论发布,因此作为答案发布。。。(只是想帮助那个有麻烦的人…)你确定你的数据库是对的吗?你能试试更改命令吗。updateOne({“locations.areas.area_id”:159},{$set:{“locations.$[l].areas.$.is_active”:false},{arrayFilters:[{“l.id”:618}]});可能提供以下详细信息,以便我们确认正确的版本:db.version();adminCommand({getParameter:1,featureCompatibilityVersion:1})@ŠtěpánZechner在mongodb 3.6.3、nodeJS本机驱动器上进行了测试,并且运行正常(更新了文档)。如果在错误的数据库中也没有错误。所以可能是别的原因。也许代码本身…@Minsky我想你是对的,我检查了数据库,版本是3.0.14,这个版本不支持arrayFilters方法:(你确定你在正确的数据库上吗?你能试试更改命令吗?.updateOne({“locations.areas.area_id”:159},{$set:{“locations.$[l].areas.$.is_active:false},),{arrayFilters:[{“l.id”:618}];可能会提供以下详细信息,以便我们确认正确的版本:db.version();db.adminCommand({getParameter:1,featureCompatibilityVersion:1});@ŠtěpánTech在mongodb 3.6.3、nodeJS本机驱动器上测试并正常工作(更新文档)。如果在错误的数据库中也没有错误。因此可能是其他原因。可能代码本身…@Minsky我想你是对的,我检查了数据库,版本为3.0.14,此版本不支持arrayFilters方法:(
mongos> db.l.find().pretty()
{
"_id" : "5e30208675b5400cb0894c52",
"locations" : [
{
"name" : "Pleasure Gardens",
"id" : 618,
"areas" : [
{
"name" : "Koi Pond",
"area_id" : 159,
"is_active" : true
}
]
}
]
mongos> db.l.updateOne( {"locations.areas.area_id": 159} , { $set:{"locations.$[loc].areas.$[are].is_active":false }}, { arrayFilters: [{ "loc.id": 618 }, { "are.area_id": 159 }] } )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
mongos> db.l.find({ "locations.areas.area_id": 159 } ,{"locations.areas.is_active":1 })
{ "_id" : "5e30208675b5400cb0894c52", "locations" : [ { "areas" : [ { "is_active" : false } ] } ] }
mongos>