MongoDB如何使用包含subdocumen的自定义键生成数组

2024-04-20 00:55:08 发布

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

好吧,使用Python和MongoDB,我尝试在数组中嵌入一个子文档,并在数组中使用自定义键值。我一直在尝试各种不同的方法来实现这一点,但我不知道我做错了什么,所以我暂时决定使用下面的工作代码。多次尝试都会导致错误:

in _check_write_command_response raise OperationFailure(error.get("errmsg"), error.get("code"), error) pymongo.errors.OperationFailure: The dotted field 'first.rule' in 'followedBy..first.rule' is not valid for storage.

代码:

 citizens.update(
    {"_id" : userPush},
    {"$push": {"followedBy":[field[1], field[2], field[3], field[0]]}})

产生:

^{pr2}$

这就是我想要的:

"_id" : ObjectId("5…asfd"), 
    "uName" : "tim0", 
    "fName" : "tim",
    "lName" : "lost",
    "pic" : null, 
    "bio" : "I <3 MongoDB", 
    "followedBy" : [
            "BobTheBomb": { 
                    "fName" : "bobby", 
                    "lName" : "knight", 
                    "uID" : NumberInt(2)
        }, 
            "Robert": { 
                    "fName" : " DROP ", 
                    "lName" : " TABLE ", 
                    "uID" : NumberInt(6)
        }
    ]

Tags: 代码inidfielduidgetmongodberror
1条回答
网友
1楼 · 发布于 2024-04-20 00:55:08

您将需要构建该数据结构,目前您说"followedBy"只是一个列表。在

所以试试看:

citizens.update(
    {"_id" : userPush},
    {"$push": {"followedBy":{field[1]: { "fName":field[2], "lName":field[3], "uID":field[0]}}}})

删除列表并用dict替换它

我真的希望这能有所帮助。在


我意识到我没有给你有效的json,我已经测试过了:

^{pr2}$

它成功了。。。在


您可能会发现错误是由您使用的修饰符引起的,我在blog上发现了以下内容:

MongoDB provides several different modifiers you can use to update documents in place, including the following (for more details see updates):

- $inc Increment a numeric field (generalized; can increment by any number)
- $set Set certain fields to new values
- $unset Remove a field from the document
- $push Append a value onto an array in the document
- $pushAll Append several values onto an array
- $addToSet Add a value to an array if and only if it does not already exist
- $pop Remove the last (or first) value of an array
- $pull Remove all occurrences of a value from an array
- $pullAll Remove all occurrences of any of a set of values from an array
- $rename Rename a field
- $bit Bitwise updates

您可能会发现,因为您正在插入许多项,而您更希望使用$pushAll或{},而不是{}。。。只是猜测。。。在

相关问题 更多 >