2018-07-04 不懂为何mongo聚合结果保存到新集合时会报错说_id重复

WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: Stats.robert index: id dup key: { : { netunion_id: 11, netunion_name: "SoloAds", offer_id: "15629001", offer_name: "LotteMart KR Android Non incent IMRO60384", offer_uniqueid: "21115629001", channel_id: 146, channel_name: "boommob", country: "KR", platform: "android", package_name: "com.lottemart.shopping", in_price: 0.8100000000000001, in_currency: "USD", out_price: 0.891, out_currency: "USD", date: "2018-07-03" } }"
}
})

上述报错是在保存聚合结果到新的集合时出现的。
不太懂既然_id时分组条件,那么聚合结果中当然应该时唯一的啊,那么为何还报错 _id 重复呢?

最后发现是matchObj位置放错了,导致匹配条件语句错误,没有匹配到结果,所以agg根本没有效果,出现同样的数据。matchObj应该放在所有for循环的外面吧。

实践中修改诸多地方后可以使用了。所以说正确agg的话不会出现主键重复的!

dbname = "Stats";
collname = "robert_copy";
var collection = db.getSiblingDB(dbname).getCollection(collname);
var userdb = "User";
var usercoll = "channel";
var usercollection = db.getSiblingDB(userdb).getCollection(usercoll);
for (var ids = 160; ids > 130; ids--) {
var userc = usercollection.find({
id: 146
});
for (var datac = userc; datac.hasNext(); ) {
var groupObj = {
netunion_id",
"netunion_name": "offer_id",
"offer_name": "offer_uniqueid",
"channel_id": "channel_name",
"country": "platform",
"package_name": "in_price",
"in_currency": "out_price",
"out_currency": "date",
},
"netunion_id": {
netunion_id"
},
"netunion_name": {
netunion_name"
},
"offer_id": {
offer_id"
},
"offer_name": {
offer_name"
},
"offer_uniqueid": {
offer_uniqueid"
},
"channel_id": {
channel_id"
},
"channel_name": {
channel_name"
},
"country": {
country"
},
"platform": {
platform"
},
"package_name": {
package_name"
},
"in_price": {
in_price"
},
"in_currency": {
in_currency"
},
"out_price": {
out_price"
},
"out_currency": {
out_currency"
},
"date": {
date"
},
"click": {
click"
},
"click_invalid": {
click_invalid"
},
"total_cvs": {
total_cvs"
},
"idp_cvs": {
idp_cvs"
},
"test_cvs": {
test_cvs"
},
}
};
var matchObj = {
/,
"clk_unix_ms": {
group"]["id"]["subchannel" + ch.replace(/./g,"")]="$" + "subchannel_" + ch.replace(/\./g,"");
groupObj["push: "match"]["channel_id"] = data["id"];
}
//print(JSON.stringify(matchObj));
//print(JSON.stringify(groupObj));
var c = collection.aggregate([matchObj, groupObj]);
var coll2 = "robert2";
for (var ldata = c; ldata.hasNext(); ) {
var sudata = ldata.next();
delete sudata['_id'];
for (let[i, key]of Object.keys(sudata).entries()) {
if (JSON.stringify(sudata[key]) === '[]') {
// print(i + ", key : " + key + " , data : " + sudata[key] );
delete sudata[key];
}
}
db.getCollection(coll2).insert(sudata);
}
//break
//c.forEach( function(doc) { print(JSON.stringify(doc));});
}
}

你可能感兴趣的:(2018-07-04 不懂为何mongo聚合结果保存到新集合时会报错说_id重复)