在 MongoDB 上使用 $push 更新数组时避免重复值

问题描述 投票:0回答:3

我想使用Python将一些值推入数组。
也许下次当我更新数组时,它会插入一些存在的值,所以它会得到一些重复的值。
我想知道是否有办法避免重复值。
我应该使用 db.collection.find() 来确定是否应该插入吗?

db.graph.insert_one({"user_id": a.url}, )
for j in a.followers:
    db.graph.update({"user_id": a.url}, {"$push": {"following": j.url}})
python mongodb mongodb-query pymongo
3个回答
36
投票

最好的方法是使用

$addToSet
运算符,确保没有重复的项目添加到集合中,并使用
$each
修饰符将多个值添加到“以下”数组中。

urls = [j.url for j in a.followers]
db.graph.update_one({"user_id": a.url}, {"$addToSet": {"following": {"$each": urls}}})

您还应该使用

update_one
方法,因为
update
已被弃用。


6
投票

我认为,您可以使用 $addToSet 运算符:https://docs.mongodb.org/manual/reference/operator/update/addToSet/


0
投票

我很懒,所以我要把我使用的代码粘贴到这里。

// 对象数组防止重复 1------------------------------------------

Dict_target_schema.index(
  { user_id: 1, wid: 1, w: 1, "exp.r_id": 1 },
  { unique: true }
);
let result = await Dict_target.findOneAndUpdate(
  // {
  //   user_id,
  //   wid,
  //   w,
  //   exp: { $not: { $elemMatch: { r_id: article_id } } },
  // },
  { user_id, wid, w, "exp.r_id": { $ne: article_id } },
  {
    $push: {
      exp: {
        r_id: article_id,
      },
    },
  },
  {
    upsert: true,
    new: true,
  }
);

// 对象数组防止重复 2-----------------

Dict_target_schema.index(
  { user_id: 1, wid: 1, w: 1 },
  { unique: true }
);
let result = await Dict_target.findOneAndUpdate(
  {
    user_id,
    wid,
    w,
    exp: { $not: { $elemMatch: { r_id: article_id } } },
  },
  {
    $push: {
      exp: {
        r_id: article_id,
      },
    },
  },
  {
    upsert: true,
    new: true,
  }
);
© www.soinside.com 2019 - 2024. All rights reserved.