从MongoDB对象数组中删除元素

时间:2013-12-12 10:58:33

标签: javascript macos bash mongodb

请看看我的MongoDB 2.4数据库: 旅行表:

{_id: 1,
"actions": [{ "type": "Flight" }, { "type": "Go" }, { "type": "Train" }, {    "type": "Sleep" }]
},
{_id: 2,
"actions": [{ "type": "Go" }, { "type": "Sleep" }, { "type": "Taxi" }]
},
{_id: 3,
"actions": [{ "type": "Flight" }]
},
{_id: 4
}

我想删除“Flight”,“Taxi”或“Train”类型的操作。 这是我的剧本:

db.trip.update({"actions": {$exists: true}}, {$pull: {"actions": {"type": {$in: ["Flight", "Taxi", "Train"]}}}});

或:

db.trip.update({"actions": {$exists: true}}, {$pull: {"actions": {"type": "Flight"}}});
db.trip.update({"actions": {$exists: true}}, {$pull: {"actions": {"type": "Train"}}});
db.trip.update({"actions": {$exists: true}}, {$pull: {"actions": {"type": "Taxi"}}});

无法解决此要求。我不知道MacOS和centOS上的mongoDB有什么区别。我在2 OS上测试了这个,测试终端和MongoHub。请帮帮我!

更新后的对象将是:

{_id: 1,
"actions": [{ "type": "Go" }, {    "type": "Sleep" }]
},
{_id: 2,
"actions": [{ "type": "Go" }, { "type": "Sleep" }]
},
{_id: 3,
"actions": []
},
{_id: 4
}

1 个答案:

答案 0 :(得分:0)

将您的查询更新为:

db.trip.update({"actions.type": "Flight"}, {$pull: {"actions": {"type": "Flight"}}});
db.trip.update({"actions.type": "Train"}}, {$pull: {"actions": {"type": "Train"}}});
db.trip.update({"actions.type": "Taxi"}}, {$pull: {"actions": {"type": "Taxi"}}});

db.trip.update({"actions" : {$in : [{type : "Flight"}, {type: "Taxi"}, {type : "Train"}]}},{$pull:{"actions" : {$in : [{type : "Flight"}, {type: "Taxi"}, {type : "Train"}]}}},false,true)
相关问题