我的DB中的文档存储了每个用户的结果数组。
数据类型:
age: {type: Number},
gender: {type: String},
result: [{ game: String,time: Number, level: Number, mistakes: Number,moves: Number }]
为了分析我的数据,我想展开
结果,例如以下文档:
{"_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" }])
但得到了以下内容:
断言:命令失败:{"ok": 0,"errmsg":"插入$out失败:{ConnectionId:1,err:\"E11000 dup licate key error index:vpdata.tmp.agg_out2.$id dup key:{:ObjectId('5ce58a 662f6fcb3b782013e3') }\", code:11000,n:0,ok:1.0}","code":16996}:聚合失败_getErrorWithCode@src/mongo/shell/utils.js:25:13doassert@src/mongo/shell/assert.js:16:14assert.commandWorked@src/mongo/shell/assert.js:290:5DBCollection.prototype.aggregate@src/mongo/shell/集合.js:1312:5@(shell):1:1
2019-05-26T19:04:05.395 0200 E QUERY[thread1]错误:命令失败:{"ok":0,"errmsg":"插入$out失败:{connect tionId:1,err:\"E11000 dup licate key error index:vpdata.tmp.agg_out.2.$id dup key:{:ObjectId('5ce58a 662f6fcb3b782013e3') }\", code:11000,n:0,ok:1.0}","code":16996}:聚合失败:_getErrorWithCode@src/mongo/shell/utils.js:25:13doassert@src/mongo/shell/assert.js:16:14assert.commandWorked@src/mongo/shell/assert.js:290:5DBCollection.prototype.aggregate@src/mongo/shell/集合.js:1312:5@(shell):1:1
我如何避免这种情况?我理解我有多个具有相同id的文档的问题,但这正是我想要的。
任何变通方法?
使用$out
,您将创建名为newCollection
的新集合。MongoDB要求每个_id
都是唯一的。该约束不能被删除,因此当您在$unways
-ing数组时,最终结果集中可能存在重复的_id
值。
作为一种解决方法,您可以引入$project
阶段并将当前_id移动到不同的字段中,这样就不会有唯一的约束。MongoDB将为所有文档生成新的_id
值,尝试:
db.userschemes.aggregate([
{ "$unwind": "$result"},
{ $addFields: { userId : "$_id" } },
{ $project: { _id: 0 } },
{ $out : "newcollection" }
])