[英]MongoDB: How to append to a string in a deep nested array
我是一个业余爱好者 web 程序员,刚开始学习 MongoDB/Mongoose,我似乎无法弄清楚如何将 append 转换为位于深层嵌套数组中的字符串。 我正在尝试 append 一个字符串到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);
});
编辑:下面是我创建 model 实例的代码
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”和“聚合管道”这两个操作,您只需要使用两者中的单个操作,
所以在这里你只需要使用更新聚合管道,使用嵌套的$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"
}
}
}
]
}
}
}
}
]
}
}
}
}
]
}
}
}
}
}]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.