Mongo错误类型需要是数组

2024-10-03 06:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试更新,将一些数据推送到mongodb中的文档中。以下运行正常:

import pymongo
import bson
from bson.objectid import ObjectId

client = pymongo.MongoClient('mongodb://localhost:27351/')
db = client.db
foo = db.foo

for i in range(2):
    nm = "xxx"+str(i)
    foo.insert_one({
            "foo":"bar", 
            "name": nm, 
            "friends": i, 
            "enemies": i+10, 
            "relations":
            {
                "friends": i,
                "enemies": i+10
            }
        })

然后我可以添加到其中一个数据中,如下所示:

foo.update_one({"name": "xxx1"},{"$push":{"comment":{"initial": "hello", "last": "world"}}})
list(foo.find())

它返回:

[{'_id': ObjectId('575f3b32f203c6069d9674ee'),
  'enemies': 10,
  'foo': 'bar',
  'friends': 0,
  'name': 'xxx0',
  'relations': {'enemies': 10, 'friends': 0}},
 {'_id': ObjectId('575f3b32f203c6069d9674ef'),
  'comment': [{'initial': 'hello', 'last': 'world'}],
  'enemies': 11,
  'foo': 'bar',
  'friends': 1,
  'name': 'xxx1',
  'relations': {'enemies': 11, 'friends': 1}}]

问题是以下错误-为什么?地址:

foo.update_one({"name": "xxx1"},{"$push":{"relations":{"enemies": 99, "friends": 88}}})

WriteError: The field 'relations' must be an array but is of type Object in document {_id: ObjectId('575f3b32f203c6069d9674ef')}


Tags: 数据nameimportiddbfoomongodbbar