删除具有对象键值猫鼬的数组元素

时间:2018-06-28 05:55:43

标签: mongodb mongoose

这是我的收藏集

{
"_id":"5b3385af20b7dc2b008ef5b9",
"name":"C",
"distances":[{"_id":"5b3460b05b2edc1bbcb0f362",
"distance":7,
"waypoint":"5b3385af20b7dc2b008ef5b9",
"status":"available"},
{"_id":"5b3460b05b2edc1bbcb0f361",
"distance":4,
"waypoint":"5b3460a15b2edc1bbcb0f360",
"status":"available"}],
"createdAt":"2018-06-27T12:40:15.457Z",
"updatedAt":"2018-06-27T12:57:50.191Z",
"__v":0
}

让我们只关注distances数组,即:

"distances":[{"_id":"5b3460b05b2edc1bbcb0f362",
"distance":7,
"waypoint":"5b3385af20b7dc2b008ef5b9",
"status":"available"},
{"_id":"5b3460b05b2edc1bbcb0f361",
"distance":4,
"waypoint":"5b3460a15b2edc1bbcb0f360",
"status":"available"}]

我想做的是,我想删除对象并更新具有"waypoint":"5b3460a15b2edc1bbcb0f360"的distances数组

到目前为止,我已经尝试过:

Model.update( {'_id': model._id}, { $pullAll: {distances: [{'waypoint': req.body.id}] } });

这不起作用。请提出解决办法。

1 个答案:

答案 0 :(得分:3)

您可以使用MongoDB的$ pull

db.collection.update(
  { },
  { $pull: { distances:  { waypoint:  req.body.id} } },
)

{multi:true}:在上述查询中添加此内容将删除所有与{waypoint:req.body.id}匹配的条目