考虑以下是我存储在集合中的文档Users
{
_id : "User1",
joined : ISODate("2011-03-02"),
likes : {
sublikes: [
{WebsiteID:'001': WebsiteName: 'ABCD'},
{WebsiteID:'002': WebsiteName: '2BC2'},
{WebsiteID:'003': WebsiteName: '3BC3'},
//...........
//...........
{WebsiteID:'999999': WebsiteName: 'SOME_NAME'}
]
}
}
现在使用 mongodb 聚合框架,我需要获取它
collection.aggregate([
{ $project: {
_id: 1,
"UserID": "$_id",
"WebsiteName": "$likes.sublikes[0]['WebsiteName']"
}
},
{ $match: { _id: 'User1'} }
], function (err, doc) {
///Not able to get the WebsiteName: 'ABCD'
});
如果我使用$unwind
的文档变得散装(特别是在上述情况下),所以我不想为了只获取数组中的第一项而展开它(不管其他人)
谁能给我有关如何访问和重命名该字段的提示?
更新1:即使我尝试使用
"WebsiteName": "$likes.sublikes.0.WebsiteName"
. 没用:-(
更新2:未解决的问题 - https://jira.mongodb.org/browse/SERVER-4589
截至目前$at
不起作用。引发错误:
{ [MongoError: exception: invalid operator '$at']
name: 'MongoError',
errmsg: 'exception: invalid operator \'$at\'',
code: 15999,
ok: 0 }
直到那时使用
$unwind
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};