gpt4 book ai didi

javascript - 我怎样才能在 Mongo Shell 中将其作为一个命令运行

转载 作者:行者123 更新时间:2023-12-02 17:04:07 25 4
gpt4 key购买 nike

db.people.update(
{ "age": "Thirty Two" }, { age: 32 }, { upsert: false }
)

db.people.update(
{ "age": "Fifty-Five" }, { age: 55 }, { upsert: false }
)

db.people.update(
{ "age": "Twenty" }, { age: 20 }, { upsert: false }
)

我在想:

db.people.update(
[{ "age": "Thirty Two" }, { age: 32 }, { upsert: false }],
[{ "age": "Fifty-Five" }, { age: 55 }, { upsert: false }],
[{ "age": "Twenty" }, { age: 20 }, { upsert: false }]
)

但这没有用..我知道我只是真的很累而且想不起来...

最佳答案

详细说明我的评论并提出 db.eval() 的替代方案,“无运算符(operator)”更新将整个匹配文档替换为更新文档(除了保留 _id ):

> db.people.find()
{ "_id" : 0, "name" : "Barney Big", "age" : 32 }
{ "_id" : 1, "name" : "Sam Small", "age" : 26 }
{ "_id" : 2, "name" : "Mindy Medium", "age" : 26 }
> db.people.update({ "age" : 32 }, { "age" : 45 })
> db.people.find()
{ "_id" : 0, "age" : 45 }
{ "_id" : 1, "name" : "Sam Small", "age" : 26 }
{ "_id" : 2, "name" : "Mindy Medium", "age" : 26 }

仅更改一个字段意味着使用 update operator喜欢 $set :

> db.people.find()
{ "_id" : 0, "name" : "Barney Big", "age" : 32 }
{ "_id" : 1, "name" : "Sam Small", "age" : 26 }
{ "_id" : 2, "name" : "Mindy Medium", "age" : 26 }
> db.people.update({ "age" : 32 }, { "$set" : { "age" : 45 } })
> db.people.find()
{ "_id" : 0, "name" : "Barney Big", "age" : 45 }
{ "_id" : 1, "name" : "Sam Small", "age" : 26 }
{ "_id" : 2, "name" : "Mindy Medium", "age" : 26 }

默认情况下,更新仅影响一个匹配文档。选项multi=true将导致更新影响所有匹配的文档:

> db.people.find()
{ "_id" : 0, "name" : "Barney Big", "age" : 32 }
{ "_id" : 1, "name" : "Larry Large", "age" : 32 }
{ "_id" : 2, "name" : "Sam Small", "age" : 26 }
{ "_id" : 3, "name" : "Mindy Medium", "age" : 26 }
> db.people.update({ "age" : 32 }, { "$set" : { "age" : 45 } })
> db.people.find()
{ "_id" : 0, "name" : "Barney Big", "age" : 45 }
{ "_id" : 1, "name" : "Larry Large", "age" : 32 }
{ "_id" : 2, "name" : "Sam Small", "age" : 26 }
{ "_id" : 3, "name" : "Mindy Medium", "age" : 26 }
> db.people.update({ "age" : 26 }, { "$set" : { "age" : 23 } }, { "multi" : true })
> db.people.find()
{ "_id" : 0, "name" : "Barney Big", "age" : 45 }
{ "_id" : 1, "name" : "Larry Large", "age" : 32 }
{ "_id" : 2, "name" : "Sam Small", "age" : 23 }
{ "_id" : 3, "name" : "Mindy Medium", "age" : 23 }

因此,要在 shell 中执行您在问题中询问的更新,我将使用 for 循环,但省去 db.eval支持多次调用db.people.update()

> updates = [
[{ "age": "Thirty Two" }, { "$set" : { "age" : 32 } }],
[{ "age": "Fifty-Five" }, { "$set" : { "age" : 55 } }],
[{ "age": "Twenty" }, { "$set" : { "age" : 20 } }]
]
> updates.forEach(function(pair) {
db.people.update(pair[0], pair[1])
})

如果您有数百个更新并且正在使用 MongoDB 2.6 或更高版本,请查看 bulk operations db.collection.update() docs中有更多信息.

关于javascript - 我怎样才能在 Mongo Shell 中将其作为一个命令运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25422054/

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