我的Mongodb API中有一个对象数组,其中每个公司对象中都包含一些公司数据,还有另一个数组则用于保存帖子。我希望能够通过id找到公司,然后通过id在posts数组内找到一个帖子,并更新column_index值。我可以按ID获取公司,然后按ID获取职位,但随后我需要能够更改该职位的column_index值。
这是我数据库中的集合:
[
{
_id: 5e98255f1c9d440000eefaf5,
company_name: 'Google',
board_posts: [
{
_id: 5e98255f1c9d440000ee5555,
column_index: 0,
},
{
_id: 5e98255f1c9d440000ee9999,
column_index: 0,
},
]
},
{
_id: 5e98255f1c9d440000eefa44,
company_name: 'Samsung',
board_posts: [
{
_id: 5e98255f1c9d440000ee1111,
column_index: 0,
},
{
_id: 5e98255f1c9d440000ee2222,
column_index: 0,
},
]
},
]
过滤条件:
const compId = '5e98255f1c9d440000eefaf5';
const postId = '5e98255f1c9d440000ee9999';
const newColumn = req.body.newColumn;
Company.aggregate([
{
$match: {
_id: ObjectId(compId),
},
},
{
$project: {
board_posts: {
$filter: {
input: "$board_posts",
as: "post",
cond: {
$eq: ["$$post._id", ObjectId(postId)],
},
},
},
},
},
])
.then((result) => {
console.log(result[0].board_posts);
res.sendStatus(201);
})
.catch((error) => {
console.log(error);
res.status(500);
});
看起来您想基于多个条件进行更新,请尝试以下操作:
Company.update({
_id:"company id",
board_posts: { $elemMatch:{
_id: "post id",
}}
},
{
"$set" : {"board_posts.$.column_index" : "index"}
}
);
更新#1:根据您的评论,一次更新多个字段,您指定的方法对于MongoDB驱动程序来说不是可接受的语法。
但是,您可以像这样单独更新它们:
Company.update({
_id:"company id",
board_posts: { $elemMatch:{
_id: "post id",
}}
},
{
"$set" : {
"board_posts.$.column_index" : "index",
"board_posts.$._id" : "id"
}
}
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句