gpt4 book ai didi

javascript - 如何增加 MongoDB 中的现有值

转载 作者:行者123 更新时间:2023-11-30 20:52:35 26 4
gpt4 key购买 nike

我正在使用 Stitch platform by MongoDB .我想在数据库中存储一个 value 和一个与该值关联的 count。现在 value 可能不是第一次出现,所以我想用 count = 1 插入 value。我可以使用 update() 使用 $inc 更新计数的现有值,或者我可以使用 upsert() 将值添加到数据库。现在,问题是,我有一个包含我的值和计数的 map,我想一次全部插入(更新/更新插入)。我不想给网络带来负担。我正在使用 insertMany() 立即插入 map 但它显然不会更新值。

那么这样做有可能吗?

附言我正在使用 javascript。

最佳答案

根据 MongoDb 3.6:

db.collection.update(查询、更新、选项)

Modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.

意思是可以使用update来upsert多个文档。

首先,您应该从只包含值的 map 创建数组。

const arrayOfValues = ['value_01', 'values_02'];

然后你应该在更新方法上使用 upsert + multi 选项:

db.foo.update({value: { $in: arrayOfValues}}, {$inc: {count:1}}, { upsert: true, multi: true });

测试输出:

> db.createCollection("test");
{ "ok" : 1 }
> db.test.insertMany([{value: "a"}, {value: "b"}, {value: "c"}];
... );
2017-12-31T12:12:18.040+0200 E QUERY [thread1] SyntaxError: missing ) after argument list @(shell):1:61
> db.test.insertMany([{value: "a"}, {value: "b"}, {value: "c"}]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5a48b8061b98cc5ac252e435"),
ObjectId("5a48b8061b98cc5ac252e436"),
ObjectId("5a48b8061b98cc5ac252e437")
]
}
> db.test.find();
{ "_id" : ObjectId("5a48b8061b98cc5ac252e435"), "value" : "a" }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e436"), "value" : "b" }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e437"), "value" : "c" }
> db.test.update({value: { $in: ["a", "b", "c"]}}, {$inc: {count:1}}, { upsert: true, multi: true });
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
> db.test.find();
{ "_id" : ObjectId("5a48b8061b98cc5ac252e435"), "value" : "a", "count" : 1 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e436"), "value" : "b", "count" : 1 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e437"), "value" : "c", "count" : 1 }
> db.test.update({value: { $in: ["a", "b", "c"]}}, {$inc: {count:1}}, { upsert: true, multi: true });
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
> db.test.find();
{ "_id" : ObjectId("5a48b8061b98cc5ac252e435"), "value" : "a", "count" : 2 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e436"), "value" : "b", "count" : 2 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e437"), "value" : "c", "count" : 2 }
> db.test.update({value: { $in: ["a", "b", "c"]}}, {$inc: {count:1}}, { upsert: true, multi: true });
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

希望对您有所帮助:)

关于javascript - 如何增加 MongoDB 中的现有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com