为$ out组合$ out mongodb插入失败,重复错误 [英] Arrgregate $out mongodb insert for $out failed duplicate Error

查看:201
本文介绍了为$ out组合$ out mongodb插入失败,重复错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查询1:我试图使用mongodb Aggregate $ lookup如下将两个集合与两个集合的选定字段组合起来

Query1: i was trying to combine two collection with selected field of both collections using mongodb Aggregate $lookup as follows

 db.col1.aggregate([
   {
       $lookup: {
          from: "col2",
          localField: "field1",    
          foreignField: "field2", 
          as: "user"
       }
   },
   {
       $unwind:"$user"
   },
   { $project: { "userfield": "$user.field",col1field:1 } },
  {$out:"new_col"}
 ])


**Error:**

*"errmsg" : "insert for $out failed: { connectionId: 4275, err: 'E11000 duplicate key error collection: db.tmp.agg_out.1 index: _id_ dup key: { : ObjectId('5b16305d145a5117552836ec') }', code: 11000, n: 0, ok: 1.0 }",
**"code" : 16996***

----------

Query2:在投影中,我添加了_id:0

Query2: In projection i have added _id:0

 db.col1.aggregate([
   {
       $lookup: {
          from: "col2",
          localField: "field1",    
          foreignField: "field2", 
          as: "user"
       }
   },
   {
       $unwind:"$user"
   },
   { $project: { "userfield": "$user.field",col1field:1 ,**_id:0**} },
  {$out:"new_col"}
 ])

**Error:**
no error and no output 

推荐答案

您的$lookup阶段仅在user字段中返回多个条目,然后将它们展平为具有相同_id值的各个子文档.您可以通过将$out阶段替换为$match来验证这一点:

Your $lookup stage simply returns multiple entries in the user field which then get flattened into individual subdocuments that have the same _id value. You can validate this by replacing the $out stage with a $match instead:

db.col1.aggregate([{
    $match: { _id: ObjectId('5b16305d145a5117552836ec') }
}

此处的关键是了解$unwind的工作方式.假设您有以下文档:

The key here is to understand how $unwind works. Imagine you have the following document:

{
    _id: 1,
    users: [ 'a', 'b' ]
}

一旦您$unwind这将获得以下两个文档:

Once you $unwind this you will get the following two documents:

{
    _id: 1,
    users: 'a'
},
{
    _id: 1,
    users: 'b'
}

因此,对于两个不同的文档,您将获得相同的_id值!

So you get the same _id value for two different documents!

现在,当您在投影中指定_id: 0时,将从所有文档中删除_id字段,这将导致MongoDB自动创建新的_id,然后再起作用.

Now, when you specify _id: 0 in your projection you remove the _id field from all documents which will cause MongoDB to automatically create new _ids which of course then works.

这篇关于为$ out组合$ out mongodb插入失败,重复错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆