在api官网上,找到了关于db.collection.update具体的说明,以下为摘录:
Use Unique Indexes
WARNING
To avoid inserting the same document more than once, only use upsert: true if the query field is uniquely indexed.
Given a collection named people where no documents have a name field that holds the value Andy.Consider when multiple clients issue the following update with upsert: true at the same time:
db.people.update(
{ name: "Andy" },
{
name: "Andy",
rating: 1,
score: 1
},
{ upsert: true }
)
If all update() operations complete the query portion before any client successfully inserts data, andthere is no unique index on the name field,then each update operation may result in an insert.
To prevent MongoDB from inserting the same document more than once, create a unique index on the namefield. With a unique index, if multiple applications issue the same update with upsert: true, exactly oneupdate() would successfully insert a new document.The remaining operations would either:
-
update the newly inserted document, or
-
fail when they attempted to insert a duplicate.
If the operation fails because of a duplicate index key error, applications may retry the operation which will succeed as an update operation.
-
与前篇提到的实验结果一致,不能满足我们应用场景。所以考虑按key分流数据
-
对应网址:https://docs.mongodb.org/manual/reference/method/db.collection.update/#update-wc