gpt4 book ai didi

javascript - 从 MongoDB 对象数组中删除元素

转载 作者:行者123 更新时间:2023-11-28 08:40:33 27 4
gpt4 key购买 nike

请看一下我的 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
}

我想删除类型为“航类”、“出租车”或“火车”的操作。这是我的脚本:

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 个操作系统上进行了测试,在终端和 MongoHub 上进行了测试。请帮助我!

更新后的对象将是:

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

最佳答案

将您的查询更新为:

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)

关于javascript - 从 MongoDB 对象数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20541608/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com