将值插入数组元素中的数组元素并返回数组长度
问题描述:
我想向位于数组元素中的字段添加值,我还想要返回数组中的元素数量只允许输入一个值。下面是数据:将值插入数组元素中的数组元素并返回数组长度
{
"_id" : ObjectId("56bb59beb32fa53064f51e3f"),
"title" : "okok",
"views" : 1,
"messages" : [
{
"authorId" : ObjectId("56bb599e8f308f1664c93011"),
"upvotes" : [], // <--- want to push a value here
"created" : ISODate("2016-02-10T15:39:42.006Z"),
"updated" : ISODate("2016-02-10T15:39:42.006Z"),
"message" : "okok"
},
{
"authorId" : ObjectId("56bb599e8f308f1664c93010"),
"upvotes" : [], // <--- insert into here plz
"created" : ISODate("2016-02-10T15:39:47.170Z"),
"updated" : ISODate("2016-02-10T15:39:47.170Z"),
"message" : "uhuhuh"
},
{
"authorId" : ObjectId("56bb599e8f308f1664c93011"),
"upvotes" : [],
"created" : ISODate("2016-02-10T15:40:01.772Z"),
"updated" : ISODate("2016-02-10T15:40:01.772Z"),
"message" : "åpåpå"
},
{
"authorId" : ObjectId("56bb599e8f308f1664c93010"),
"upvotes" : [],
"created" : ISODate("2016-02-10T15:40:04.889Z"),
"updated" : ISODate("2016-02-10T15:40:04.889Z"),
"message" : "påpåpå<br /><br />påå"
},
{
"authorId" : ObjectId("56bb599e8f308f1664c93010"),
"upvotes" : [],
"created" : ISODate("2016-02-11T12:36:26.006Z"),
"updated" : ISODate("2016-02-11T12:36:26.006Z"),
"message" : "testt"
},
{
"authorId" : ObjectId("56bb599e8f308f1664c93013"),
"upvotes" : [],
"created" : ISODate("2016-02-11T12:36:31.514Z"),
"updated" : ISODate("2016-02-11T12:36:31.514Z"),
"message" : "tetetet"
}
]
}
我有文件_id
和阵列元素created
字段以定位该阵列中的元素。
我试过如下:
}
$match: {
_id: retard.ObjectId(data.id),
'messages.created': data.created
}
}, {
$group: {
'messages.$.upvotes': {
$addToSet: 'myTestValueToInsert'
}
}
}, {
$project: {
numUpvotes: {
$size: '$upvotes'
}
}
}, {
multi: false
}
但是得到一个错误。我一直在阅读聚合文档,但这些示例稍微缺乏!
答
的aggregation
框架并不旨在并且不能用于插入或更新的文件(this
是一个扩展的能力,而不是一个例外),更确切地说,它可以过程数据记录,并返回计算结果。
您可以使用update
查询来更新匹配的子文件:
var myTestValueToInsert = 1;
db.t.update({
"_id":retard.ObjectId(data.id),
"messages.created":data.created
},
{
"$addToSet":{"messages.$.upvotes":myTestValueToInsert}
})
然后,检索修改后的数组的大小,可以按下面总IT:
db.t.aggregate([
{$match:{"_id":retard.ObjectId(data.id)}},
{$unwind:"$messages"},
{$match:{"messages.created":data.created}},
{$project:{"size":{$size:"$messages.upvotes"},"_id":0}}
])
如果您正在使用shell,有一个很好的wrapper
来更新并获取更新的文档,但您需要获取客户端文档中的数组大小:
db.t.findAndModify({
"query":{"_id":retard.ObjectId(data.id),"messages.created":data.created},
"update":{$addToSet:{"messages.$.upvotes":myTestValueToInsert}},
"new":true
})
***哇+1 ***。第一段现在真的打开了我的眼睛,我从来没有意识到聚合可以用来处理数据。我一直认为聚合是一种高级查询(您可以在其中更新记录/插入)。重新阅读文档后,它开始变得更有意义。希望你的段落在官方的mongodb文档中,为我节省了时间和头痛! –