本文介绍了如何在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?
发布评论