NodeJS,Mongoose如何通过聚合查询模式



我是MongoDB的新手,我正在尝试使用聚合$set管道更新我的文档。然而,我已经尝试了几天,仍然没有成功。我试图通过查询ObjectId并将匹配的结果(单数(替换为我指定的键值对来进行更新。我在Mongo Compass上测试了聚合,它很有效。有人知道如何在NodeJS中使用聚合吗?

更新一个查询我尝试了

let query = {"_id": ObjectId('theObjectIamUpdating')};
response = await newForm.updateOne(query, payload);

聚合查询我尝试过

response = await newForm.updateOne([
{$match: {"_id": ObjectId(update_id)}},
{$set: {
"data.velo": [
[1, 2, 3], [5, 7]
]
}}
]);

newForm Mongoose架构

data: {
date: {
type: Array,
required: false,
trim: true,
},
speed: {
type: Array,
required: false,
trim: true,
},
velo: {
type: Array,
required: false,
trim: true,
}
},
calc: {
date: {
type: Array,
required: false,
trim: true,
},
speed: {
type: Array,
required: false,
trim: true,
},
velo: {
type: Array,
required: false,
trim: true,
}
}

UPDATE我的updateOne((已成功,但我的文档没有得到更新。

我在记录等待的响应后得到的结果

Data received  {
acknowledged: true,
modifiedCount: 0,
upsertedId: null,
upsertedCount: 0,
matchedCount: 0
}
POST /api/compute/calculate 200 16 - 79.821 ms

此外,这是我尝试Mongo Compass 时使用的MongoDB聚合

pipeline = $match > $set
**$match**
{
"_id": ObjectId('62e2295060280132dbcee4ae')
}
**$set**
{
"data.velo": [
[1, 2, 3], [5, 7]
]
}

其中velo是数据中的键值对之一,并且设置结果仅替换data.velo中的数据。

正如评论部分提到的那样,我确实发现了updateOne()语法方面的一些错误。

updateOne((的正确语法

let response = await Form_csv_metadata2.updateOne({ '_id': [update_id] }, [
{//delete this line $match: {"_id": ObjectId(update_id)},
$set: {
"data.velo": [[1, 2, 3], [5, 7]]
}}
]);

正如官方文件所提到的,参数是:Query、UpdateData和Option。我犯了这个错误,因为我的查询被放在了UpdateData()参数($match(中。它本身应该是一个作为查询的参数(查询使用与find()相同的语法(。另一个注意事项是,如果我使用管道聚合,它应该是{ $match: {...}, $set: {...} }而不是{ {$match: {...}}, {$set: {...}} }

最新更新