如何在mongoDB中使用聚合查询使用findOneAndUpdate?

编程入门 行业动态 更新时间:2024-10-28 03:32:06
本文介绍了如何在mongoDB中使用聚合查询使用findOneAndUpdate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我将nestJS用作与MongoDB连接的后端.我可以在我的架构中访问嵌套数组:

I am using nestJS as a backend connected with MongoDB. I am able to access a nested array in my schema which is:

{ "id": "productId", "name": "productName", "price": "productPrice", "Categories": [ { "_id": "catId", "name": "catName", "Subcategories": [ { "_id": "subcatId", "name": "subcatName" }, { "_id": "subcatId", "name": "subcatName" }, ] }, { "_id": "catId", "name": "catName", "Subcategories": [ { "_id": "subcatId", "name": "subcatName" }, { "_id": "subcatId", "name": "subcatName" }, ] } ] } ]

我能够通过以下方式访问类别和子类别:

I am able to access categories and subcategories via the following:

db.collection.aggregate([ { $match: { "id": "productId" } }, { $unwind: "$Categories" }, { $project: { "_id": "$Categories._id", "name": "$Categories.name" } } ])

db.collection.aggregate([ { $match: { "id": "productId" } }, { $unwind: "$Categories" }, { $match: { "Categories._id": "catId" } }, { $unwind: "$Categories.Subcategories" }, { $project: { _id: "$Categories.Subcategories._id", name: "$Categories.Subcategories.name" } } ])

我现在面临的问题是如何使用findOneAndUpdate方法更新类别或子类别.

The problem I am facing now is how to update a category or subcategory using the findOneAndUpdate method.

我该如何访问正确的类别/子类别_id进行更新?

How would i go about accessing the correct category/subcategory _id to update?

提前谢谢.

推荐答案

您要使用 arrayFilters 像这样:

db.collection.updateOne( { //query to match document }, { $set: { "Categories.$[cat].name": newValue } }, //set name to new value in categories. { $set: { "Categories.Subcategories.$[subCat].name": newValue2 } }, //set name to new value in categories. { arrayFilters: [ { "cat._id": categoryId }, { "subCat._id": subCategoryId } ] } )

很明显,您可以替换name和_id字段以匹配和更新对象中的任何其他字段.

Obviously you can replace the name and _id fields to match and update any other fields in the object.

更多推荐

如何在mongoDB中使用聚合查询使用findOneAndUpdate?

本文发布于:2023-11-22 07:10:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616448.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   mongoDB   findOneAndUpdate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!