MongoDB Aggregate $project中,如果想新加一列常数,如何写?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MongoDB Aggregate $project中,如果想新加一列常数,如何写?相关的知识,希望对你有一定的参考价值。

例如(C#代码)
var query = new BsonDocument


"$project",
new BsonDocument

"_id",0,
"x",false,
"y",1234


;
AggregateResult result = books.Aggregate(query);
其中x,y为新加入的列。当然上述代码被报错。

1. Test Data
Data in JSON format, shows the hosting provider for website.
website.json
"_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com"
"_id" : 2, "domainName" : "test2.com", "hosting" : "aws.amazon.com"
"_id" : 3, "domainName" : "test3.com", "hosting" : "aws.amazon.com"
"_id" : 4, "domainName" : "test4.com", "hosting" : "hostgator.com"
"_id" : 5, "domainName" : "test5.com", "hosting" : "aws.amazon.com"
"_id" : 6, "domainName" : "test6.com", "hosting" : "cloud.google.com"
"_id" : 7, "domainName" : "test7.com", "hosting" : "aws.amazon.com"
"_id" : 8, "domainName" : "test8.com", "hosting" : "hostgator.com"
"_id" : 9, "domainName" : "test9.com", "hosting" : "cloud.google.com"
"_id" : 10, "domainName" : "test10.com", "hosting" : "godaddy.com"

Imports into a “website” collection.
> mongoimport -d testdb -c website --file website.json
connected to: 127.0.0.1
Mon Jan 13 14:30:22.662 imported 10 objects

Note
If the collection is existed, add --upsert option to override the data.

> mongoimport -d testdb -c website --file website.json --upsert

2. Grouping Example
Uses db.collection.aggregate and $group to perform the data grouping.
2.1 The following example groups by the “hosting” field, and display the total sum of each hosting.
> db.website.aggregate(

$group : _id : "$hosting", total : $sum : 1

);

Output

"result" : [

"_id" : "godaddy.com",
"total" : 1
,

"_id" : "cloud.google.com",
"total" : 2
,

"_id" : "aws.amazon.com",
"total" : 4
,

"_id" : "hostgator.com",
"total" : 3

],
"ok" : 1


The equivalent SQL.
SELECT hosting, SUM(hosting) AS total
FROM website
GROUP BY hosting

2.2 Add sorting with $sort.
> db.website.aggregate(

$group : _id : "$hosting", total : $sum : 1
,

$sort : total : -1

);

Output – Display “total” in descending order. For ascending order, uses $sort : total : 1.

"result" : [

"_id" : "aws.amazon.com",
"total" : 4
,

"_id" : "hostgator.com",
"total" : 3
,

"_id" : "cloud.google.com",
"total" : 2
,

"_id" : "godaddy.com",
"total" : 1

],
"ok" : 1


2.3 Add $match condition, groups by “hosting” for “aws.amazon.com” only.
> db.website.aggregate(

$match : hosting : "aws.amazon.com"
,

$group : _id : "$hosting", total : $sum : 1

);

Output

"result" : [

"_id" : "aws.amazon.com",
"total" : 4

],
"ok" : 1


More Examples
Refer to this official MongoDB Aggregation guide for more advance aggregation and group examples.

3. Exports Grouping Result to CSV or JSON
Often times, we need to export the grouping results in csv or JSON format. To solve it, inserts the group results in a new collection, and exports the new collection via mongoexport.
3.1 Set the group results in a variable. In this case, the variable name is “groupdata”.
> var groupdata = db.website.aggregate(

$group : _id : "$hosting", total : $sum : 1
,

$sort : total : -1

);

3.2Inserts groupdata.toArray() into a new collection.
> db.websitegroup.insert(groupdata.toArray());

> db.websitegroup.find().pretty()
"_id" : "aws.amazon.com", "total" : 4
"_id" : "hostgator.com", "total" : 3
"_id" : "cloud.google.com", "total" : 2
"_id" : "godaddy.com", "total" : 1
>

3.3 Exports the collection “websitegroup” to a csv file.
c:\> mongoexport -d testdb -c websitegroup -f _id,total -o group.csv --csv
connected to: 127.0.0.1
exported 4 records

group.csv
_id,total
"aws.amazon.com",4.0
"cloud.google.com",2.0
"godaddy.com",1.0
"hostgator.com",3.0

3.4 Exports the collection “websitegroup” to a JSON file.
c:\> mongoexport -d testdb -c websitegroup -o group.json
connected to: 127.0.0.1
exported 4 records

group.json
"_id" : "aws.amazon.com", "total" : 4
"_id" : "cloud.google.com", "total" : 2
"_id" : "godaddy.com", "total" : 1
"_id" : "hostgator.com", "total" : 3

4. Large Sort Operation
Changed in version 2.6 – Read this Memory Restrictions
In MongoDB, the in-memory sorting have a limit of 100M, to perform a large sort, you need enable allowDiskUse option to write data to a temporary file for sorting.
To avoid the sort exceeded memory limit error, enable the allowDiskUse option.
db.website.aggregate(
[
$group : _id : "$hosting", total : $sum : 1 ,
$sort : total : -1
],
allowDiskUse: true
);

References
MongoDB Aggregation
MongoDB db.collection.aggregate()
Aggregation Pipeline Limits
MongoDB Hello World Example
Tags : group mongodb sort
Share this article on
TwitterFacebookGoogle+

Reader also read :
MongoDB : Sort exceeded memory limit of 104857600 bytes
Spring Data MongoDB – Aggregation Grouping Example
Spring Data MongoDB – Select fields to return
MongoDB – Allow remote access
参考技术A

不知道报的什么错,我没用过C#的driver,但是我感觉C#的人不像javascript的人那样爱用不确定数量的参数,所以我想C#的Aggregate方法接受的参数应该是数组、IList或者IEnumerable之类的东西吧,你试试:

AggregateResult result = books.Aggregate(new []query);

之类的看看行不行。

本回答被提问者采纳

Mongodb中数据聚合之聚合管道aggregate

在之前的两篇文章<Mongodb中数据聚合之基本聚合函数count、distinct、group >和<Mongodb中数据聚合之MapReduce >中,我们已经对数据聚合提供了两种实现方式,今天,在这篇文章中,我们讲讲在Mongodb中的另外一种数据聚合实现方式——聚合管道aggregate。


面对着广大用户对数据统计的需求,Mongodb从2.2版本之后便引入了新的功能聚合框架(aggregation framework),它是数据聚合的新框架,这个概念类似于数据处理中的管道。每个文档通过一个由多个节点组成的管道,每个节点都有自己的特殊的作用(分组、过滤等),文档经过由多个节点组成的管道后最终得到输出结果。管道基本的功能有两种:(1)对文档进行过滤,筛选出符合条件的文档;(2)对文档进行变换,改变文档的输出结构。


聚合管道的使用方式:db.collection.aggregate();

对于管道中的多个节点可以使用以下几种管道操作符,下面对各种管道操作符的功能进行描述:

$project:修改文档的结构(重命名、增加或删除域),也可以用于创建计算结果以及嵌套文档。
$match:过滤数据,只输出符合条件的文档。
$limit:限制MongoDB聚合管道返回的文档数。
$skip:在聚合管道中跳过指定数量的文档。
$unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
$group:将集合中的文档分组,可用于统计结果。
$sort:文档排序输出。
$geoNear:输出接近某一地理位置的有序文档。


举两个简单的例子:

db.article.aggregate(
    { $project : {
        title : 1 ,
        author : 1 ,
    }}
 );

db.articles.aggregate( [
                        { $match : { score : { $gt : 70, $lte : 90 } } },
                        { $group: { _id: user, count: { $sum: 1 } } }
                       ] );

下面对聚合管道使用过程中需要注意的地方进行说明:

(1)管道的是具有先后顺序的。
(2)$group操作目前是在内存中处理的,因此,不能对大量的文档进行使用该种方式进行分组操作;
(3)使用$unwind对数组中的字段值进行拆分时需要注意不能忘记写$符号,如{$unwind:"$tags"},tags字段前面有个$号;
(4)MongoDB 24.对内存做了优化,如果$sort出现在$limit之前,$sort只会对前$limit个文档进行操作,在内存中也只会保留前$limit个文档,节省了内存
(5)$sort操作是在内存中进行的,如果其占有的内存超过物理内存的10%,程序会产生错误

(6)管道的输出结果大小不能大于16M,超过会出现错误。
(7)如果一个管道操作符在执行过程中所占用的内存超过系统内存容量的10%,则会报错;
(8)聚合管道可以提供很好的性能和一致的接口,使用起来比较简单,对于一些简单的固定的聚集操作可以使用管道,但是对于一些复杂的、大量数据集的聚合任务还是使用MapReduce。

至此,关于Mongodb数据库内的数据聚合操作的简单描述便结束了,如果大家想更深入的学习了解,我觉得官网才是最好的教材,奋斗

以上是关于MongoDB Aggregate $project中,如果想新加一列常数,如何写?的主要内容,如果未能解决你的问题,请参考以下文章

MongoDB 聚合

Mongodb中数据聚合之聚合管道aggregate

MongoDB聚合(aggregate)常用操作及示例

Mongodb的聚合和管道

MongoDB:聚合aggregate

MongoDB 聚合(管道与表达式)