| Name | Description |
|---|---|
| $project | Reshapes a document stream. $project can rename, add, or remove fields as well as create computed values and sub-documents. |
| $match | Filters the document stream, and only allows matching documents to pass into the next pipeline stage.$match uses standard MongoDB queries. |
| $limit | Restricts the number of documents in an aggregation pipeline. |
| $skip | Skips over a specified number of documents from the pipeline and returns the rest. |
| $unwind | Takes an array of documents and returns them as a stream of documents. |
| $group | Groups documents together for the purpose of calculating aggregate values based on a collection of documents. |
| $sort | Takes all input documents and returns them in a stream of sorted documents. |
| $geoNear | Returns an ordered stream of documents based on proximity to a geospatial point. |
1. $project: 数据投影,主要用于重命名、增加和删除字段,例如:
db.article.aggregate(
{ $project : {
title : 1 ,
author : 1 ,
}}
);
db.article.aggregate(
{ $project : {
_id : 0 ,
title : 1 ,
author : 1
}});
db.article.aggregate(
{ $project : {
title : 1,
doctoredPageViews : { $add:["$pageViews", 10] }
}});
db.article.aggregate(
{ $project : {
title : 1 ,
page_views : "$pageViews" ,
bar : "$other.foo"
}});
db.article.aggregate(
{ $project : {
title : 1 ,
stats : {
pv : "$pageViews",
foo : "$other.foo",
dpv : { $add:["$pageViews", 10] }
}
}});
$match的语法和查询表达式(db.collection.find())的语法相同
db.articles.aggregate( [
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
] );
$limit的参数只能是一个正整数
db.article.aggregate(
{ $limit : 5 });
$skip参数也只能为一个正整数
db.article.aggregate(
{ $skip : 5 });
经过$skip管道操作符处理后,前五个文档被“过滤”掉
5. $unwind:将数组元素拆分为独立字段
例如:article文档中有一个名字为tags数组字段:
{ "_id" : ObjectId("528751b0e7f3eea3d1412ce2"),
{
"result" : [
{
"_id" : ObjectId("528751b0e7f3eea3d1412ce2"),
"author" : "Jone",
"title" : "A book",
"tags" : "good"
},
{
"_id" : ObjectId("528751b0e7f3eea3d1412ce2"),
"author" : "Jone",
"title" : "A book",
"tags" : "fun"
},
{
"_id" : ObjectId("528751b0e7f3eea3d1412ce2"),
"author" : "Jone",
"title" : "A book",
"tags" : "good"
}
],
"ok" : 1
}
{ "result" : [ ], "ok" : 1 }
将$tags改为$tag因不存在该字段,该文档被忽略,输出的结果为空
at printStackTrace (src/mongo/shell/utils.js:37:15)
at DBCollection.aggregate (src/mongo/shell/collection.js:897:9)
at (shell):1:12
Sat Nov 16 19:16:54.488 JavaScript execution failed: aggregate failed: {
"errmsg" : "exception: $unwind: value at end of field path must be an array",
"code" : 15978,
"ok" : 0
} at src/mongo/shell/collection.js:L898
$group的时候必须要指定一个_id域,同时也可以包含一些算术类型的表达式操作符:
db.article.aggregate(
{ $group : {
_id : "$author",
docsPerAuthor : { $sum : 1 },
viewsPerAuthor : { $sum : "$pageViews" }
}});
2.$group操作目前是在内存中进行的,所以不能用它来对大量个数的文档进行分组。
7. $sort : 对文档按照指定字段排序
使用方式如下:
db.users.aggregate( { $sort : { age : -1, posts: 1 } });
注意:1. 如果将$sort放到管道前面的话可以利用索引,提高效率
2. MongoDB 24.对内存做了优化,在管道中如果$sort出现在$limit之前的话,$sort只会对前$limit个文档进行操作,这样在内存中也只会保留前$limit个文档,从而可以极大的节省内存
3. $sort操作是在内存中进行的,如果其占有的内存超过物理内存的10%,程序会产生错误
8. $goNear
$goNear会返回一些坐标值,这些值以按照距离指定点距离由近到远进行排序
具体使用参数见下表:
| Field | Type | Description |
|---|---|---|
| near | GeoJSON point orlegacy coordinate pairs | The point for which to find the closest documents. |
| distanceField | string | The output field that contains the calculated distance. To specify a field within a subdocument, use dot notation. |
| limit | number | Optional. The maximum number of documents to return. The default value is 100. See also the num option. |
| num | number | Optional. The num option provides the same function as the limitoption. Both define the maximum number of documents to return. If both options are included, the num value overrides the limit value. |
| maxDistance | number | Optional. A distance from the center point. Specify the distance in radians. MongoDB limits the results to those documents that fall within the specified distance from the center point. |
| query | document | Optional. Limits the results to the documents that match the query. The query syntax is the usual MongoDB read operation query syntax. |
| spherical | Boolean | Optional. If true, MongoDB references points using a spherical surface. The default value is false. |
| distanceMultiplier | number | Optional. The factor to multiply all distances returned by the query. For example, use the distanceMultiplier to convert radians, as returned by a spherical query, to kilometers by multiplying by the radius of the Earth. |
| includeLocs | string | Optional. This specifies the output field that identifies the location used to calculate the distance. This option is useful when a location field contains multiple locations. To specify a field within a subdocument, usedot notation. |
| uniqueDocs | Boolean | Optional. If this value is true, the query returns a matching document once, even if more than one of the document’s location fields match the query. If this value is false, the query returns a document multiple times if the document has multiple matching location fields. See $uniqueDocsfor more information. |
db.places.aggregate([
{
$geoNear: {
near: [40.724, -73.997],
distanceField: "dist.calculated",
maxDistance: 0.008,
query: { type: "public" },
includeLocs: "dist.location",
uniqueDocs: true,
num: 5
}
}
])
{
"result" : [
{ "_id" : 7,
"name" : "Washington Square",
"type" : "public",
"location" : [
[ 40.731, -73.999 ],
[ 40.732, -73.998 ],
[ 40.730, -73.995 ],
[ 40.729, -73.996 ]
],
"dist" : {
"calculated" : 0.0050990195135962296,
"location" : [ 40.729, -73.996 ]
}
},
{ "_id" : 8,
"name" : "Sara D. Roosevelt Park",
"type" : "public",
"location" : [
[ 40.723, -73.991 ],
[ 40.723, -73.990 ],
[ 40.715, -73.994 ],
[ 40.715, -73.994 ]
],
"dist" : {
"calculated" : 0.006082762530298062,
"location" : [ 40.723, -73.991 ]
}
}
],
"ok" : 1}
注意: 1.使用$goNear只能在管道处理的开始第一个阶段进行
2.必须指定distanceField,该字段用来决定是否包含距离字段
3.$gonNear和geoNear命令比较相似,但是也有一些不同:distanceField在$geoNear中是必选的,而在geoNear中是可选的;includeLocs在$geoNear中是string类型,而在geoNear中是boolen类型。
管道操作符作为“键”,所对应的“值”叫做管道表达式。例如上面例子中{$match:{status:"A"}},$match称为管道操作符,而{s tatus:"A"}称为管道表达式,它可以看做是管道操作符的操作数(Operand),每个管道表达式是一个文档结构,它是由字段名、字段值、和一些表达式操作符组成的,例如上面例子中管道表达式就包含了一个表达式操作符$sum进行累加求和。
每个管道表达式只能作用于处理当前正在处理的文档,而不能进行跨文档的操作。管道表达式对文档的处理都是在内存中进行的。除了能够进行累加计算的管道表达式外,其他的表达式都是无状态的,也就是不会保留上下文的信息。累加性质的表达式操作符通常和$group操作符一起使用,来统计该组内最大值、最小值等,例如上面的例子中我们在$group管道操作符中使用了具有累加的$sum来计算总和。
| Name | Description |
|---|---|
| $addToSet | Returns an array of all the unique values for the selected field among for each document in that group. |
| $first | Returns the first value in a group. |
| $last | Returns the last value in a group. |
| $max | Returns the highest value in a group. |
| $min | Returns the lowest value in a group. |
| $avg | Returns an average of all the values in a group. |
| $push | Returns an array of all values for the selected field among for each document in that group. |
| $sum | Returns the sum of all the values in a group. |
| Name | Description |
|---|---|
| $and | Returns true only when all values in its input array are true. |
| $or | Returns true when any value in its input array are true. |
| $not | Returns the boolean value that is the opposite of the input value. |
| Name | Description |
|---|---|
| $cmp | Compares two values and returns the result of the comparison as an integer. |
| $eq | Takes two values and returns true if the values are equivalent. |
| $gt | Takes two values and returns true if the first is larger than the second. |
| $gte | Takes two values and returns true if the first is larger than or equal to the second. |
| $lt | Takes two values and returns true if the second value is larger than the first. |
| $lte | Takes two values and returns true if the second value is larger than or equal to the first. |
| $ne | Takes two values and returns true if the values are not equivalent. |
| Name | Description |
|---|---|
| $add | Computes the sum of an array of numbers. |
| $divide | Takes two numbers and divides the first number by the second. |
| $mod | Takes two numbers and calcualtes the modulo of the first number divided by the second. |
| $multiply | Computes the product of an array of numbers. |
| $subtract | Takes two numbers and subtracts the second number from the first. |
| Name | Description |
|---|---|
| $concat | Concatenates two strings. |
| $strcasecmp | Compares two strings and returns an integer that reflects the comparison. |
| $substr | Takes a string and returns portion of that string. |
| $toLower | Converts a string to lowercase. |
| $toUpper | Converts a string to uppercase. |
| Name | Description |
|---|---|
| $dayOfYear | Converts a date to a number between 1 and 366. |
| $dayOfMonth | Converts a date to a number between 1 and 31. |
| $dayOfWeek | Converts a date to a number between 1 and 7. |
| $year | Converts a date to the full year. |
| $month | Converts a date into a number between 1 and 12. |
| $week | Converts a date into a number between 0 and 53 |
| $hour | Converts a date into a number between 0 and 23. |
| $minute | Converts a date into a number between 0 and 59. |
| $second | Converts a date into a number between 0 and 59. May be 60 to account for leap seconds. |
| $millisecond | Returns the millisecond portion of a date as an integer between 0 and 999. |
| Name | Description |
|---|---|
| $cond | A ternary operator that evaluates one expression, and depending on the result returns the value of one following expressions. |
| $ifNull | Evaluates an expression and returns a value. |
776



被折叠的 条评论
为什么被折叠?



