代码之家  ›  专栏  ›  技术社区  ›  Sudhanshu Gaur

MongoDB在MongoDB对象数组中推送用户提供的对象数组,这样就不会有任何重复

  •  1
  • Sudhanshu Gaur  · 技术社区  · 6 年前

    假设我有一个文档集

    { "id":1, "arr":[{"a":1, "b":2, "c":3}, {"a":6, "b":0, "c":8},....]}
    { "id":2, "arr":[{"a":7, "b":1, "c":4}, {"a":5, "b":2, "c":6},....]}
    

    let user_id: 2;
    let user_arr = [{"a":7, "b":1, "c":9}, {"a":1, "b":6, "c":3},.....]
    

    现在我想将用户提供的arr文档推送到用户的 arr 对于 user_id 由用户提供,这样(a,b)两个值的组合不会为他/她重复。

    (a:7, b:1) 所以它不会被插入,但是 (a:1, b:6) {"a":1, "b":6, "c":3} 在arr中插入。

    1 回复  |  直到 6 年前
        1
  •  1
  •   mickl    6 年前

    你可以用 $elemMatch 与…结合 $not $push 不会复制该数组中的任何其他子文档。尝试:

    db.col.update({ id: user_id, arr: { $not: { $elemMatch: { a: 7, b: 1 } } } }, { $push: { arr: { a:7, b:1, c:9} } })
    

    附加条件 id 将强制此操作修改一个或零个文档。

    bulkWrite

    db.col.bulkWrite(
        [
            { 
                updateOne : {
                        "filter" : { id: 2, arr: { $not: { $elemMatch: { a: 7, b: 1 } } } },
                        "update" : { $push: { arr: { a:7, b:1, c:9} } }
                    }
            },
            { 
                updateOne : {
                        "filter" : { id: 2, arr: { $not: { $elemMatch: { a: 1, b: 6 } } } },
                        "update" : { $push: { arr: { a:1, b:6, c:3} } }
                    }
            }
        ]
    );
    

    作为回应,您将得到:

    {
        "acknowledged" : true,
        "deletedCount" : 0,
        "insertedCount" : 0,
        "matchedCount" : 1,
        "upsertedCount" : 0,
        "insertedIds" : {
    
        },
        "upsertedIds" : {
    
        }
    }
    

    这意味着两个条件中只有一个与文档匹配 身份证件 2