获取错误“pipe道元素3不是对象错误”,而试图使用聚合查找和更新

我正在使用node js mongodb driver &试图更新文档中的object array内的对象数组。

文档集合的模式是这样的:

在这里输入图像说明

我想要的是 :

对于order no = 1 & items.qty=2 & tax rate = 25 ,将tax to "cst" & taxratetype to "flat"更新tax to "cst" & taxratetype to "flat"

我试过的:

 db.OrderInfo.aggregate( {$match:{"orderno":"1"}}, {$unwind:'$items'}, { $match: { 'items.qty' : 2} },function(err,result1){ if(err){ throw(err); }else{ indexes = result1[0].items.taxes.map(function(obj, index) { if(obj.taxrate == 25) { return index; } }).filter(isFinite); var updateData = {}; updateData["items.$.taxes."+indexes[0]+".tax"]="cst"; updateData["items.$.taxes."+indexes[0]+".taxratetype"]="flat"; db.OrderInfo.update({ "orderno":"1",'items.qty': 2,'items.taxes.taxrate': 25 },{$set: updateData },function(err,result2){ console.log(result2); }); } }); 

目前,我正在使用db.eval从节点运行此脚本,但稍后将完成相同的更改。

获取此错误:

{“name”:“MongoError”,“message”:“Error:command failed:{\ n \ t \”ok \“:0,\ n \ t \”errmsg \“:\”pipeline元素3不是object \“,\ n \ t \”code \“:15942 \ n}:聚合失败:\ n_getErrorWithCode@src/mongo/shell/utils.js:25:13 \ ndoassert@src/mongo/shell/assert.js :13:14个\ nassert.commandWorked@src/mongo/shell/assert.js:267:5个\ nDBCollection.prototype.aggregate@src/mongo/shell/collection.js:1312:5 \ n_funcs1 @:1:31 \ n“,”ok“:0,”errmsg“:”错误:命令失败:{\ n \ t \“ok \”:0,\ n \ t \“errmsg \”:\“pipeline元素3不是object \“,\ n \ t \”code \“:15942 \ n}:聚合失败:\ n_getErrorWithCode@src/mongo/shell/utils.js:25:13 \ ndoassert@src/mongo/shell/assert.js :13:14个\ nassert.commandWorked@src/mongo/shell/assert.js:267:5个\ nDBCollection.prototype.aggregate@src/mongo/shell/collection.js:1312:5 \ n_funcs1 @:1:31 \ N”, “代码”:139}

我知道从这个问题https://jira.mongodb.org/browse/SERVER-831 ,我不能使用直接更新命令,因此尝试此解决方法。 任何其他的这种更新方法也适用于我。

编辑:根据@ titi23给出的答案,我曾尝试使用[]也内function。 它没有给我任何错误,但我的价值也没有得到更新。

查询中的两个问题:

1)在aggregate查询中缺less[]

2)更新方法不需要税率条款。 它会发现嵌套的文件和来自聚合的索引将用于更新的目的。

有关如何使用它的更多信息,请参阅聚合定义 。

语法 – db.collection.aggregate(pipeline,options)

pipeline – array – 一系列数据聚合操作或阶段。

尝试以下操作: –

 db.OrderInfo.aggregate([ {$match:{"orderno":"1"}}, {$unwind:'$items'}, { $match: { 'items.qty' : 2} }]).toArray( function(err,result1){ if(err){ throw(err); } else{ console.log(result[0]); //See is there any record here indexes = result1[0].items.taxes.map(function(obj, index) { if(obj.taxrate == 25) { return index; } }).filter(isFinite); var updateData = {}; updateData["items.$.taxes."+indexes[0]+".tax"]="cst"; updateData["items.$.taxes."+indexes[0]+".taxratetype"]="flat"; db.OrderInfo.update({ "orderno":"1",'items.qty': 2}, /*Remove the tax rate clause from here..*/ {$set: updateData },function(err,result2){ console.log(result2); }); } }); 

它不应该抛出错误。

编辑:toArray()与聚合,看看是否有帮助。 已经更新了查询。