mongodb聚合框架-获取嵌套数组的第一个文档的字段 [英] mongodb aggregation framework - Fetch first document's field of the nested array
问题描述
考虑以下内容是我存储在集合Users
Consider the following is my document stored in collection 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聚合框架,我需要获取
Now using mongodb aggregation framework I need to fetch that
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
,则文档会变大(在上述情况下尤其如此),因此,我不想为了仅获取数组中的第一项而展开它(与其他项无关)
If I use $unwind
the document becomes bulk (specifically in the above case), So I don't want to unwind it for getting only first item in an array (irrespective of others)
谁能给我提示如何访问并重命名该字段?
更新:1:即使我尝试使用
"WebsiteName": "$likes.sublikes.0.WebsiteName"
进行投影.没用:-(
Can anyone give me hints on how to access is and rename that field?
Update 1: Even I tried to project with
"WebsiteName": "$likes.sublikes.0.WebsiteName"
. Didn't work :-(
更新:2:未解决的问题- https://jira.mongodb.org/browse/SERVER-4589
Update 2: Open issue - https://jira.mongodb.org/browse/SERVER-4589
到目前为止,$at
无法正常工作.引发错误:
As of now $at
does not work. Throws an error:
{ [MongoError: exception: invalid operator '$at']
name: 'MongoError',
errmsg: 'exception: invalid operator \'$at\'',
code: 15999,
ok: 0 }
然后使用
$unwind
Till then using
$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);
};
推荐答案
获得结果的最简单方法是使用普通的find查询和$slice
运算符:
The easiest way to achieve your result is using a normal find query and the $slice
operator:
db.collection.find( {_id: "User1"}, {"likes.sublikes": {$slice: 1}} )
聚合框架(从MongoDB 2.4.1开始)不支持$slice
或数组索引(投票/监视功能请求: SERVER-4589 )
The aggregation framework (as at MongoDB 2.4.1) does not support $slice
or array indexes (vote/watch feature requests: SERVER-6074 and SERVER-4589).
您可以使用$unwind
,$group
和$first
运算符在聚合框架中执行此操作,例如:
You could do this in aggregation framework using $unwind
, $group
and the $first
operator, eg:
db.collection.aggregate([
{ $match: {
_id : "User1"
}},
{ $unwind: "$likes.sublikes" },
{ $group: {
_id: "$_id",
like: { $first: "$likes.sublikes" }
}},
{ $project: {
_id: 0,
"UserID": "$_id",
"WebsiteName": "$like.WebsiteName"
}}
])
正常的$slice
应该是性能最高的选项.
The normal $slice
should be the most performant option.
这篇关于mongodb聚合框架-获取嵌套数组的第一个文档的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!