在mongodb数据库中插入新字段

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

我是一个mongodb和pymongo的初学者,我正在做一个项目,我有一个学生的mongodb集合。我想在集合中的每个元素中添加一个新的字段,特别是一个学生的地址(这个字段显然是以空的形式添加的,以后将由我来填充)。

然而,当我尝试使用这个特定的例子来添加一个新的字段时,我得到了以下语法错误。

 client = MongoClient('mongodb://localhost:27017/') #connect to local mongodb

 db = client['InfoSys']   #choose infosys database
 students = db['Students']

 students.update(  {  $set : {"address":1} }  ) #set address field to every column (error happens here)

我该如何解决这个错误?

python mongodb pymongo
1个回答
1
投票

前面的回答是正确的,但看起来你的问题可能更多的是与PyMongo和它如何管理更新集合有关。https:/pymongo.readthedocs.ioenstableapipymongocollection.html。

根据文档,看起来你可能想使用'update_many()'函数,但你仍然需要将你的查询(本例中的所有文档)作为第一个参数,第二个参数是对所有记录执行的操作。你仍然需要将你的查询(本例中是所有文档)作为第一个参数,第二个参数是对所有记录执行的操作。

client = MongoClient('mongodb://localhost:27017/') #connect to local mongodb

db = client['InfoSys']   #choose infosys database
students = db['Students']

sudents.update_many({}, {$set : {"address":1}})

1
投票

你使用更新操作的方式是错误的。更新操作的语法如下。

db.collection.update(
   <query>,
   <update>,
   <options>
)

主参数 <query> 根本就没有提到。它至少要像 {}在你的情况下,下面的查询就可以了。

db.students.update(
  {}, // To update the all the documents.
  {$set : {"address": 1}}, // Update the address field.
  {multi: true} // To do multiple updates, otherwise Mongo will just update the first matching document.
)

所以,在python中,你可以使用 update_many 以达到这个目的。所以,它会像。

students.update_many(
  {},
  {"$set" : {"address": 1}}
)

你可以阅读更多关于这个操作 此处.


0
投票

我通过迭代我的集合中的每一个元素,并将地址字段插入到每一个元素中,解决了我的问题。

 cursor = students.find({})
 for student in cursor :
      students.update_one(student, {'$set': {'address': '1'}})    
© www.soinside.com 2019 - 2024. All rights reserved.