如何解决MongoDB:如何在深层嵌套数组中附加到字符串
我是一个业余爱好者Web程序员,刚开始学习MongoDB / Mongoose,而且我似乎无法弄清楚如何将其追加到位于深层嵌套数组中的字符串中。我正在尝试在hours: String
的末尾附加一个字符串。以下是我正在使用的架构:
const TestSchema = new Schema({
userID: Number,years: [
{
year: Number,months: [{
month: Number,days: [{
day: Number,hours: String
}]
}]
}
]
});
这是我到目前为止所拥有的。我在这里尝试扩展此答案:https://stackoverflow.com/a/56589089。但这给了我一个Cannot specify arrayFilters and a pipeline update
错误。
TestModel.findOneAndUpdate(
{ "years.months.days.day": 12 },[
{
$set: {
"years.$[index1].months.$[index2].days.$[index3].hours": {
$concat: [
"$years.$[index1].months.$[index2].days.$[index3].hours"," 44:44:44"
]
}
}
}
],{
arrayFilters: [
{ "index1.year": 2020 },{ "index2.month": 7 },{ "index3.day": 12 }
]
}
).catch(error => {
console.log("error>>" + error);
});
编辑:以下是我用来创建模型实例的代码
var test = new TestModel({
userID: 5,years: [{
year: 2020,months: [{
month: 7,days: [{
day: 12,hours: "4:4:4 5:5:5"
}]
}]
}]
})
test.save().then(function(){
console .log("testSaved>>" + !test.isNew);
});
解决方法
更新不同时支持“ arrayFilters”和“聚合管道”这两个操作,您只需使用两者中的单个操作,
因此在这里,您只需要使用update aggregation pipeline,使用嵌套的$map
,
TestModel.findOneAndUpdate({
years: {
$elemMatch: {
year: 2020,months: {
$elemMatch: {
month: 7,days: { $elemMatch: { day: 12 } }
}
}
}
}
},[{
$set: {
years: {
$map: {
input: "$years",as: "y",in: {
$mergeObjects: [
"$$y",{
months: {
$map: {
input: "$$y.months",as: "m",in: {
$mergeObjects: [
"$$m",{
days: {
$map: {
input: "$$m.days",as: "d",in: {
$mergeObjects: [
"$$d",{
hours: {
$cond: {
if: {
$and: [
{ $eq: ["$$y.year",2020] },{ $eq: ["$$m.month",7] },{ $eq: ["$$d.day",12] }
]
},then: { $concat: ["$$d.hours"," 44:44:44"] },else: "$$d.hours"
}
}
}
]
}
}
}
}
]
}
}
}
}
]
}
}
}
}
}]
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。