考虑以下是我的文档存储在集合中 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'}
]
}
}
Run Code Online (Sandbox Code Playgroud)
现在使用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'
});
Run Code Online (Sandbox Code Playgroud)
如果我使用$unwind文档变成批量(特别是在上面的情况下),所以我不想放松它只获取数组中的第一项(不论其他人)
任何人都可以给我提示如何访问并重命名该字段?
"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 }
Run Code Online (Sandbox Code Playgroud)
直到然后使用
$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);
};
Run Code Online (Sandbox Code Playgroud)
小智 10
实现结果的最简单方法是使用常规查找查询和$slice运算符:
db.collection.find( {_id: "User1"}, {"likes.sublikes": {$slice: 1}} )
Run Code Online (Sandbox Code Playgroud)
聚合框架(如MongoDB 2.4.1)不支持$slice或数组索引(投票/观看功能请求:SERVER-6074和SERVER-4589).
你可以使用聚合框架做到这一点$unwind,$group与$first运营商,如:
db.collection.aggregate([
{ $match: {
_id : "User1"
}},
{ $unwind: "$likes.sublikes" },
{ $group: {
_id: "$_id",
like: { $first: "$likes.sublikes" }
}},
{ $project: {
_id: 0,
"UserID": "$_id",
"WebsiteName": "$like.WebsiteName"
}}
])
Run Code Online (Sandbox Code Playgroud)
正常$slice应该是最高性能的选项.