要在 MongoDB 中添加字段,可以使用 $set 操作符来更新现有文档。
例如,假设我们有以下文档:
{
"name": "John",
"age": 30
}
要添加一个新的字段,我们可以使用以下命令:
db.collection.updateOne(
{ "name": "John" },
{ $set: { "occupation": "developer" } }
)
这将在名为“John”的文档中添加一个“occupation”字段,并将其设置为“developer”。
如果要添加多个字段,请使用类似的语法:
db.collection.updateOne(
{ "name": "John" },
{
$set: {
"occupation": "developer",
"city": "New York",
"country": "USA"
}
}
)
这将在相同的文档中添加三个新字段。
如果您想要在新的文档中添加字段,请使用 insertOne 命令而不是 updateOne。例如:
db.collection.insertOne(
{
"name": "Jane",
"age": 25,
"occupation": "designer"
}
)
这将创建一个新的文档,并在其中添加“occupation”字段。