0

编辑:

文件结构:

{"tags" : ["a"], "name" : "a", "creator" : "Nick here", "users" : [ "Nick here"], "connected" : 1, "ra" : 0.3967885102611035, "_id" : ObjectId("513c3e42071a103c09000003")}

我对 MongoDB $pull 运算符有疑问。它不会从数组中删除值。这是我的查询:

db.rooms.update({users: ["Nick here"]},{$pull: {users: ["Nick here"]}})

用户字段如下所示:

(...) ,"users" : [ "Nick here" ],(...)


如果我这样写:

db.rooms.update({users: "Nick here"},{$pull: {users: ["Nick here"]}})

或者

db.rooms.update({users: "Nick here"},{$pull: {users: "Nick here"}})

返回一个错误:

无法将 $pull/$pullAll 修饰符应用于非数组


这些查询有什么问题?当“用户”字段为空时,我想拉/推用户的昵称并删除文档。

提前致谢, 米哈乌

4

1 回答 1

1

我写了测试...检查你的语法。询问:

db.rooms.update({'users': 'Nick here'}, {$pull: {'users': 'Nick here'}})

可能在您的查询中需要用到{ multi: true }。例如:

db.rooms.update({'users': 'Nick here'}, {$pull: {'users': 'Nick here'}}, { multi: true })

完整日志:

MongoDB shell version: 2.2.3
connecting to: so
> db.rooms.insert({"tags" : ["a"], "name" : "a", "creator" : "Nick here", "users" : [ "Nick here"], "connected" : 1, "ra" : 0.3967885102611035, "_id" : ObjectId("513c3e42071a103c09000003")} )
> db.rooms.findOne()
{
    "_id" : ObjectId("513c3e42071a103c09000003"),
    "tags" : [
        "a"
    ],
    "name" : "a",
    "creator" : "Nick here",
    "users" : [
        "Nick here"
    ],
    "connected" : 1,
    "ra" : 0.3967885102611035
}
> db.rooms.update({'users': 'Nick here'}, {$pull: {'users': 'Nick here'}})
> db.rooms.findOne()
{
    "_id" : ObjectId("513c3e42071a103c09000003"),
    "connected" : 1,
    "creator" : "Nick here",
    "name" : "a",
    "ra" : 0.3967885102611035,
    "tags" : [
        "a"
    ],
    "users" : [ ]
}
>
于 2013-03-10T11:19:40.993 回答