gpt4 book ai didi

arrays - 从 mongoDB 集合中删除数组项

转载 作者:太空宇宙 更新时间:2023-11-04 00:42:42 25 4
gpt4 key购买 nike

我正在尝试执行以下操作,如果有人可以提供帮助将是很大的帮助

我想从项目数组中删除一个项目

 {
"_id" : ObjectId("56e8c56a71cfa3fbe528c91b"),
"shipping" : 6.7800000000000002,
"subTotal" : 201,
"totalCost" : 207.7800000000000011,
"order_status" : "queued",
"ordered_by" : "John Sims",
"ordered_by_id" : "56e8c50a71cfa3fbe5288a48",
"created_at" : ISODate("2016-03-16T02:31:06.723Z"),
"items" : [

{
"created_at" : "2008-12-17T11:01:23.460Z",
"quantity" : 1,
"country" : "Australia",
"state" : "NSW",
"suburb" : "Sydney",
"location" : "Sydney,NSW,Australia",
"longitude" : "151.1228434",
"latitude" : "-33.7904955",
"genre" : "Rock",
"cost" : "67",
"product_status" : "pending",
"product_by" : "Paul Dirac",
"item" : "CD",
"cart_id" : "56e8c56271cfa3fbe528c918"
},

{
"created_at" : "2008-12-17T11:01:23.460Z",
"quantity" : 1,
"country" : "Australia",
"state" : "QLD",
"suburb" : "Brisbane",
"location" : "Brisbane,NSW,Australia",
"longitude" : "151.1228434",
"latitude" : "-33.7904955",
"genre" : "",
"cost" : "67",
"product_status" : "pending",
"product_by" : "Paul Dirac",
"item" : "DVD",
"cart_id" : "56e8c56571cfa3fbe528c919"
}
]
}

基于如下条件

// Updates an existing order in the DB.
exports.updateArray = function(req, res) {
Order.findById(req.params.id, function (err, order) {
if (err) { return handleError(res, err); }
if(!order) { return res.send(404); }
order.update(
// query
{

},

// update
{
$pull:{
items:{
"item" : "CD"
}
}
}
);
order.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, order);
});
});
};

现在更新代码运行,并在从 shell 执行以下代码时从项目中删除项目

db.getCollection('orders').update(
// query
{

},

// update
{$pull:{
items:{
item:'CD'
}
}
},

// options
{
"multi" : false, // update only one document
"upsert" : false // insert a new document, if no existing document match the query
}
);

但是,当运行放置或删除请求时,这不会从特定文档的项目数组中删除该项目。如果有人可以帮助我找出需要更改的代码以使其通过 HTTP 请求发生,那就太好了。

谢谢

最佳答案

db.collection.findOneAndUpdate({_id:'56e8c56a71cfa3fbe528c91b'},
{$pull:{"items.item":"cd"}},{new:true},function(err,object{
});
您可以在 mongodb 查询中使用 $pull 。我在 ndoe js 中的 mongoose 中使用了这个查询,它可能对我有用..

关于arrays - 从 mongoDB 集合中删除数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36026179/

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