英文:
How can I update specific elements in an array in MongoDB using an array
问题
我有一个对象
customer = {
customerName: "Rajesh",
customerNum: "899111111111",
products: [
{
productName: "ABC",
productPrize: "100",
deliveyDate: "20/2/2022"
},{
productName: "def",
productPrize: "22",
deliveyDate: "22/2/2022"
}
]
}
和一个数组,我只改变了产品名称:
updatedProduct = [ { productName: "cdf" },{ productName: "qqq" } ]
如何使用这个(updatedProduct)数组仅更新MongoDB中customer对象的产品名称。
我尝试使用$set,但它没有按预期工作。
英文:
I have an object
customer = {
customerName:"Rajesh",
customerNum:"899111111111",
products:[
{
productName:"ABC",
productPrize:"100",
deliveyDate:"20/2/2022"
},{
productName:"def",
productPrize:"22",
deliveyDate:"22/2/2022"
}
]
}
and I have an array where I changed the product names only :
updatedProduct = [ { productName:"cdf"},{ productName:"qqq"} ]
How can I update only product names of the customer object in MongoDB using this( updatedProduct ) array.
I tried the use $set but it didn't worked as expected
答案1
得分: 1
以下是翻译好的代码部分:
updatedProduct = [{ productName: "cdf" }, { productName: "qqq" }]
db.customer.udpateOne(
{ customerName: "Rajesh" },
[
{
$set: {
products: {
$map: {
input: { $range: [0, updatedProduct.length, 1] },
as: "i",
in: {
$mergeObjects: [
{ $arrayElemAt: ["$products", "$$i"] },
{ $arrayElemAt: [updatedProduct, "$$i"] },
]
}
}
}
}
}
]
)
英文:
You can try this one:
updatedProduct = [{ productName: "cdf" }, { productName: "qqq" }]
db.customer.udpateOne(
{ customerName: "Rajesh" },
[
{
$set: {
products: {
$map: {
input: { $range: [0, updatedProduct.length, 1] },
as: "i",
in: {
$mergeObjects: [
{ $arrayElemAt: ["$products", "$$i"] },
{ $arrayElemAt: [updatedProduct, "$$i"] },
]
}
}
}
}
}
]
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论