文件结构:
{"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修饰符应用于非数组
这些查询有什么问题? 当'users'字段为空时,我想拉/推用户的笔记并删除文档。
提前致谢, 米哈尔
答案 0 :(得分: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" : [ ]
}
>