问题
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"
}
}
])
The problem I am facing now is how to update a category or subcategory using the findOneAndUpdate method.
How would i go about accessing the correct category/subcategory _id to update?
Thanks in advance.
回答1:
You want to use arrayFilters like so:
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 } ] }
)
Obviously you can replace the name
and _id
fields to match and update any other fields in the object.
回答2:
You can update category data like this,
You can update exact reference matched in your condition using .$
in your update
db.collection.findOneAndUpdate({
'id':"productId",
'Categories._id':"catId1"
},{
$set:{
'Categories.$.name':"catName7"
}
},{
new:true
})
I'll have to check for SubCategory as its two level down, I'll check & post same late
来源:https://stackoverflow.com/questions/59986592/how-to-use-findoneandupdate-using-an-aggregated-query-in-mongodb