0
我想向位于数组元素中的字段添加值,我还想要返回数组中的元素数量只允许输入一个值。下面是数据:将值插入数组元素中的数组元素并返回数组长度
{
"_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
}
但是得到一个错误。我一直在阅读聚合文档,但这些示例稍微缺乏!
***哇+1 ***。第一段现在真的打开了我的眼睛,我从来没有意识到聚合可以用来处理数据。我一直认为聚合是一种高级查询(您可以在其中更新记录/插入)。重新阅读文档后,它开始变得更有意义。希望你的段落在官方的mongodb文档中,为我节省了时间和头痛! –