为$ out插入失败

时间:2019-05-26 17:06:55

标签: mongodb aggregation-framework

我在数据库中的文档为每个用户存储了一系列结果。

数据类型:

age: {type: Number}, 
gender: {type: String},
result: [{ game: String,time: Number, level: Number, mistakes: Number,moves: Number }]

为了分析我的数据,我想unwind得出结果, 例如以下文件:

{"_id":"5ce58a662f6fcb3b782013e3","age":10,"gender":"Male","result":[{"_id":"5ce58a662f6fcb3b782013e9","game":"puzzle","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e8","game":"puzzle","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e7","game":"puzzle","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e6","game":"memory","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e5","game":"memory","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e4","game":"memory","time":20,"level":3,"mistakes":5,"moves":50}],"__v":0}]

将被划分为6个文档,并以相同的 userId 存储在新集合中。

我尝试运行:

 db.userschemes.aggregate([{ "$unwind": "$result"},{ $out : "newcollection" }])

但得到以下信息:

  

assert:命令失败:{           “ ok”:0,           “ errmsg”:“为$ out插入失败:{connectionId:1,err:\” E11000 dup licate key错误索引:vpdata.tmp.agg_out.2。$ id dup   键:{:ObjectId('5ce58a 662f6fcb3b782013e3')} \“,代码:11000,n:0,   好的:1.0}“,           “代码”:16996}:聚合失败   _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:16:14   assert.commandWorked@src/mongo/shell/assert.js:290:5   DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1312:5   @(shell):1:1

     

2019-05-26T19:04:05.395 + 0200 E查询[thread1]错误:命令   失败:{           “ ok”:0,           “ errmsg”:“为$ out插入失败:{connectionId:1,err:\” E11000 dup licate key错误索引:vpdata.tmp.agg_out.2。$ id dup   键:{:ObjectId('5ce58a 662f6fcb3b782013e3')} \“,代码:11000,n:0,   好的:1.0}“,           “代码”:16996}:聚合失败:   _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:16:14   assert.commandWorked@src/mongo/shell/assert.js:290:5   DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1312:5   @(shell):1:1

如何避免这种情况?我了解我有多个具有相同ID的文档的问题,但这正是我想要的。

有什么解决方法吗?

1 个答案:

答案 0 :(得分:0)

使用$out来创建名为newcollection的新集合。 MongoDB要求每个_id都是唯一的。无法删除该约束,因此,当您$unwind-创建数组时,最终结果集中可能有重复的_id值。

作为一种解决方法,您可以引入$project阶段并将当前的_id移到其他字段中,这样就不会对其施加唯一约束。 MongoDB将为所有文档生成新的_id值,请尝试:

db.userschemes.aggregate([
    { "$unwind": "$result"},     
    { $addFields: { userId : "$_id" } },
    { $project: { _id: 0 } },
    { $out : "newcollection" }
])