SequoiaDB的聚合函數aggregate()在Java開發中的應用

聚合函數

概述

聚合函數提供了對集合中的原始數據記錄進行統計計算的能力.通過使用聚合函數,用戶能夠直接從集合中提取數據記錄並獲取所需的統計結果.聚合函數提供的操作接口類似於集合中的查詢操作,不同的是聚合函數還提供了一系列函數及操作對查詢結果進行處理.

聚集符

概述

參數名 描述 示例
$project 選擇需要輸出的字段名,"1"表示輸出,"0"表示不輸出,還可以實現字段的重命名 { KaTeX parse error: Expected '}', got 'EOF' at end of input: …d: 0, aliase: "field3" } }
$match 實現從集合中選擇匹配條件的記錄,相當於SQL語句的where {$match: { field: { $lte: value } } }
$limit 限制返回的記錄條數 { $limit: 10 }
$skip 控制結果集的開始點,即跳過結果集中指定條數的記錄 { $skip: 5 }
$group 實現對記錄的分組,類似於SQL的group by語句,"_id"指定分組字段 { KaTeX parse error: Expected '}', got 'EOF' at end of input: group: { _id: "field" } }
$sort 實現對結果集的排序,“1"代表升序,”-1"代表降序 { $sort: { field1: 1, field2: -1, … } }

應用舉例(快速入門)

這裏的快速入門以兩種方式(shell和json開發)演示聚合函數的功能.

Shell

創建集合

> var db = new Sdb("localhost",11810)
> db.createCS("foo")
> db.foo.createCL("bar")

插入數據

> db.foo.bar.insert({ name: "張三", income: 10000, age: 31, city: "北京" })
> db.foo.bar.insert({ name: "李四", income: 25000, age: 28, city: "上海" })
> db.foo.bar.insert({ name: "王五", income: 15000, age: 32, city: "上海" })
> db.foo.bar.insert({ name: "趙六", income: 30000, age: 40, city: "北京" })

使用聚合函數篩選

使用"$match"子操作將集合中年齡大於30的數據記錄篩選出來

>db.foo.bar.aggregate({$match:{age:{$gt:30}}})

經過篩選後,數據爲:

{ name: "張三", income: 10000, age: 31, city: "北京" }
{ name: "王五", income: 15000, age: 32, city: "上海" }
{ name: "趙六", income: 30000, age: 40, city: "北京" }

JSON開發

創建數據庫連接

 //創建數據庫連接
 public Sequoiadb getConnection() {   
 	Sequoiadb sequoiadb = new Sequoiadb("192.168.248.128:11810", "sdbadmin", "sdbadmin");
 	return sequoiadb;
 }

創建並獲得集合

//創建集合空間
public void crtCS() {
 	Sequoiadb sequoiadb = getConnection();
    sequoiadb.createCollectionSpace("foo");
}
//創建集合
public void crtCL() {
	Sequoiadb sequoiadb = getConnection();
    sequoiadb.getCollectionSpace("foo").createCollection("bar");
}
//獲取集合
public DBCollection getCollection() {
	Sequoiadb sequoiadb = getConnection();
    CollectionSpace cs = sequoiadb.getCollectionSpace("foo");
    DBCollection cl = cs.getCollection("bar");
    return cl;
}

插入數據

//插入數據
public void insert() {
	DBCollection dbCollection = getCollection();
    List<BSONObject> list = new ArrayList<BSONObject>();
    BSONObject bsonObject1 = new BasicBSONObject();
    bsonObject1.put("name", "張三");
    bsonObject1.put("age", 31);
    bsonObject1.put("income", 10000);
    bsonObject1.put("city", "北京");
	......
	list.add(bsonObject1);
	......
	dbCollection.insert(list);
}

查詢數據

//查詢數據
public void query() {
	DBCollection dbCollection = getCollection();
    // 查詢所有記錄,並把查詢結果放在遊標對象中
    DBCursor cursor = dbCollection.query();
    try {
    	while (cursor.hasNext()) {
        	BSONObject record = cursor.getNext();
            // 可將返回記錄映射成自定義實體對象(Person)
            Person person = record.as(Person.class);
            System.out.println(person.toString());
        }
    } catch (BaseException e) {
    	System.out.println("Sequoiadb driver error, error description:" + e.getErrorType());
    } catch (Exception e) {
    	e.printStackTrace();
    } finally {
    	cursor.close();
    }
}

使用聚合函數查詢數據

 //聚合函數
 public void test() {
 	DBCollection dbCollection = getCollection();
    List<BSONObject> list = new ArrayList<BSONObject>();
    BSONObject bsonObject1 = new BasicBSONObject();
    bsonObject1.put("$gt", 30);
    BSONObject bsonObject2 = new BasicBSONObject();
    bsonObject2.put("age", bsonObject1);
    BSONObject bsonObject3 = new BasicBSONObject();
    bsonObject3.put("$match", bsonObject2);
    list.add(bsonObject3);
    DBCursor cursor = dbCollection.aggregate(list);
    try {
    	while (cursor.hasNext()) {
        BSONObject record = cursor.getNext();
        // 可將返回記錄映射成自定義實體對象(Person)
        Person person = record.as(Person.class);
        System.out.println(person.toString());
        }
    } catch (BaseException e) {
    	System.out.println("Sequoiadb driver error, error description:" + e.getErrorType());
    } catch (Exception e) {
    	e.printStackTrace();
    } finally {
    	cursor.close();
    }
}

輸出結果:

Person{name='張三', age=31, income=10000, city='北京'}
Person{name='王五', age=32, income=15000, city='上海'}
Person{name='趙六', age=40, income=30000, city='北京'}

Java API中聚合函數的介紹

public DBCursor com.sequoiadb.base.DBCollection.aggregate(List<BSONObject> objs) throws BaseException

對集合進行聚合操作的函數.

參數:

objs-規則列表的bson對象,不能爲空

拋出:

BaseException - If error happens.

應用(代碼片段)

$project

語法

{ $project: { <字段名1:0 | 1 | "$新字段名1">, [字段名2: 0 | 1 | "$新字段名2", ... ] } }

描述

projectSQLselect,使project類似SQL中的select語句,通過使用project操作可以從記錄中篩選出所需字段:

  • 如果字段的值爲1,表示選出
  • 如果字段的值爲0,表示不選
  • 通過"$新字段名"可以實現把字段重命名爲"新字段名"

如果記錄不存在所選字段,則以如下格式輸出:“field”:null,其中field爲不存在的字段名.對嵌套對象使用點操作符(.)引用字段名

示例

使用$project展示集合bar中的name字段

public void project() {
	DBCollection dbCollection = getCollection();
    List<BSONObject> list = new ArrayList<BSONObject>();
    BSONObject bsonObject1 = new BasicBSONObject();
    bsonObject1.put("name", 1);
    bsonObject1.put("age", 0);
    bsonObject1.put("income", 0);
    //bsonObject1.put("city", 1);
    BSONObject bsonObject2 = new BasicBSONObject();
    bsonObject2.put("$project", bsonObject1);
    list.add(bsonObject2);
    DBCursor cursor = dbCollection.aggregate(list);
    try {
    	while (cursor.hasNext()) {
        BSONObject record = cursor.getNext();
        // 可將返回記錄映射成自定義實體對象(Person)
        Person person = record.as(Person.class);
        System.out.println(person.toString());
    	}
    } catch (BaseException e) {
    	System.out.println("Sequoiadb driver error, error description:" + e.getErrorType());
    } catch (Exception e) {
    	e.printStackTrace();
    } finally {
    	cursor.close();
    }
}

輸出結果:

Person{name='張三', age=null, income=null, city='null'}
Person{name='李四', age=null, income=null, city='null'}
Person{name='王五', age=null, income=null, city='null'}
Person{name='趙六', age=null, income=null, city='null'}

$match

語法

$match與db.collectionspace.collection.find()方法中的cond參數完全相同.

描述

通過$match可以從集合中選擇匹配條件的記錄.

示例

該操作表示返回集合foo.bar中年齡大於30和城市爲北京的記錄.

public void match() {
	DBCollection dbCollection = getCollection();
    List<BSONObject> list = new ArrayList<BSONObject>();
    BSONObject bsonObject1 = new BasicBSONObject();
    bsonObject1.put("city", "北京");
    BSONObject bsonObject3 = new BasicBSONObject();
    bsonObject3.put("$gt", 30);
    BSONObject bsonObject2 = new BasicBSONObject();
    bsonObject2.put("age", bsonObject3);
    BasicBSONList arr = new BasicBSONList();
    arr.put("0", bsonObject2);
    arr.put("0", bsonObject1);
    BSONObject bsonObject4 = new BasicBSONObject();
    bsonObject4.put("$and", arr);
    BSONObject bsonObject5 = new BasicBSONObject();
    bsonObject5.put("$match", bsonObject4);
    list.add(bsonObject5);
    DBCursor cursor = dbCollection.aggregate(list);
    try {
    	while (cursor.hasNext()) {
        	BSONObject record = cursor.getNext();
            // 可將返回記錄映射成自定義實體對象(Person)
            Person person = record.as(Person.class);
            System.out.println(person.toString());
        }
   	} catch (BaseException e) {
    	System.out.println("Sequoiadb driver error, error description:" + e.getErrorType());
    } catch (Exception e) {
    	e.printStackTrace();
    } finally {
    	cursor.close();
    }
}

輸出結果:

Person{name='張三', age=31, income=10000, city='北京'}
Person{name='趙六', age=40, income=30000, city='北京'}

$limit

語法

{ $limit: <返回記錄數> }

描述

$limit實現在結果集中限制返回的記錄條數.如果指定的記錄條數大於實際的記錄總數,那麼返回實際的記錄總數.

示例

該操作表示集合foo.bar中讀取前3條記錄。

public void limit() {
	DBCollection dbCollection = getCollection();
    List<BSONObject> list = new ArrayList<BSONObject>();
    BSONObject bsonObject1 = new BasicBSONObject();
    bsonObject1.put("$limit", 3);
    list.add(bsonObject1);
    DBCursor cursor = dbCollection.aggregate(list);
    try {
    	while (cursor.hasNext()) {
            BSONObject record = cursor.getNext();
            // 可將返回記錄映射成自定義實體對象(Person)
            Person person = record.as(Person.class);
            System.out.println(person.toString());
        }
    } catch (BaseException e) {
    	System.out.println("Sequoiadb driver error, error description:" + e.getErrorType());
    } catch (Exception e) {
    	e.printStackTrace();
    } finally {
   		cursor.close();
    }
}

輸出結果:

Person{name='張三', age=31, income=10000, city='北京'}
Person{name='李四', age=28, income=25000, city='上海'}
Person{name='王五', age=32, income=15000, city='上海'}

$sort

語法

{ $sort: { 字段1: -1 | 1 [, 字段2: -1 | 1, ... ] } }

描述

$sort用來指定結果集的排序規則.對嵌套對象使用點操作符(.)引用字段名

  • 字段取值爲-1表示降序排列
  • 字段取值爲1表示升序排列

示例

該操作表示從集合foo.bar中讀取記錄,並以age的字段值進行降序排序(1表示升序,-1表示降序);

當記錄間age字段值相同時,則以income字段值進行升序排序。

 public void sort() {
 	DBCollection dbCollection = getCollection();
    List<BSONObject> list = new ArrayList<BSONObject>();
    BSONObject bsonObject1 = new BasicBSONObject();
    bsonObject1.put("age", -1);
    bsonObject1.put("income", 1);
    BSONObject bsonObject2 = new BasicBSONObject();
    bsonObject2.put("$sort", bsonObject1);
    list.add(bsonObject2);
    DBCursor cursor = dbCollection.aggregate(list);
    try {
    	while (cursor.hasNext()) {
        	BSONObject record = cursor.getNext();
            // 可將返回記錄映射成自定義實體對象(Person)
            Person person = record.as(Person.class);
            System.out.println(person.toString());
        }
    } catch (BaseException e) {
    	System.out.println("Sequoiadb driver error, error description:" + e.getErrorType());
    } catch (Exception e) {
   		e.printStackTrace();
    } finally {
    	cursor.close();
    }
}

輸出結果:

Person{name='趙六', age=40, income=30000, city='北京'}
Person{name='王五', age=32, income=15000, city='上海'}
Person{name='張三', age=31, income=10000, city='北京'}
Person{name='李四', age=28, income=25000, city='上海'}

$skip

語法

 $skip: <記錄數> }

描述

$skip參數控制結果集的開始點,即跳過結果集中指定條數的記錄.如果跳過的記錄數大於總記錄數,返回0條記錄.

示例

該操作表示從集合foo.bar中讀取記錄,並跳過前面2條,從第3條記錄開始返回。

public void skip() {
	DBCollection dbCollection = getCollection();
    List<BSONObject> list = new ArrayList<BSONObject>();
    BSONObject bsonObject = new BasicBSONObject("$skip", 2);
    list.add(bsonObject);
    DBCursor cursor = dbCollection.aggregate(list);
    try {
    	while (cursor.hasNext()) {
        	BSONObject record = cursor.getNext();
            // 可將返回記錄映射成自定義實體對象(Person)
            Person person = record.as(Person.class);
            System.out.println(person.toString());
        }
    } catch (BaseException e) {
    	System.out.println("Sequoiadb driver error, error description:" + e.getErrorType());
    } catch (Exception e) {
    	e.printStackTrace();
    } finally {
    	cursor.close();
    }
}

輸出結果:

Person{name='王五', age=32, income=15000, city='上海'}
Person{name='趙六', age=40, income=30000, city='北京'}

$group

語法

{ $group: { _id:"$分組字段名", 顯示字段名: { 聚集函數: "$字段名"},[顯示字段名2: { 聚集函數: "$字段名"}, ...] } }

描述

$group實現對結果集的分組,類似SQL中的group by語句.

首先指定分組鍵(_id),通過"_id"來標識分組字段,分組字段可以是單個,也可以是多個,格式如下:

單個分組鍵:

{_id:"$field"}

多個分組鍵

{_id:{field1:"$field1",field2:"$field2",...}}

示例

該操作表示從集合foo.bar中讀取記錄,並按city字段進行分組.

 public void group() {
 	DBCollection dbCollection = getCollection();
    List<BSONObject> list = new ArrayList<BSONObject>();
    BSONObject bsonObject1 = new BasicBSONObject("_id","$city");
    BSONObject bsonObject2 = new BasicBSONObject("$group",bsonObject1);
    list.add(bsonObject2);
    DBCursor cursor = dbCollection.aggregate(list);
    try {
    	while (cursor.hasNext()) {
        	BSONObject record = cursor.getNext();
        	// 可將返回記錄映射成自定義實體對象(Person)
        	Person person = record.as(Person.class);
            System.out.println(person.toString());
        }
    } catch (BaseException e) {
    	System.out.println("Sequoiadb driver error, error description:" + e.getErrorType());
    } catch (Exception e) {
    	e.printStackTrace();
    } finally {
    	cursor.close();
    }
}

輸出結果:

Person{name='李四', age=28, income=25000, city='上海'}
Person{name='張三', age=31, income=10000, city='北京'}

$group支持的聚集函數

函數名 描述
$addtoset 將字段添加到數組中,相同的字段值只會添加一次
$first 取分組中第一條記錄中的字段值
$last 取分組中最後一條記錄中的字段值
$max 取分組中字段值最大的
$min 取分組中字段值最小的
$avg 取分組中字段值的平均值
$push 將所有字段添加到數組中,即使數組中已經存在相同的字段值,也繼續添加
$sum 取分組中字段值的總和
$count 對記錄分組後,返回表所有的記錄條數
$addtoset

記錄分組後,使用$addtoset 將指定字段值添加到數組中,相同的字段值只會添加一次。對嵌套對象使用點操作符(.)引用字段名。

示例

如下操作對記錄分組後將指定字段值添加到數組中輸出:

> db.foo.bar.aggregate({ $group: { _id: "$dep", Dep: { $first: "$dep" }, addtoset_major: { $addtoset: "$major" } } })
{
  "Dep": "物電學院",
  "addtoset_major": [
    "物理學",
    "光學",
    "電學"
  ]
}
{
  "Dep": "計算機學院",
  "addtoset_major": [
    "計算機科學與技術",
    "計算機軟件與理論",
    "計算機工程"
  ]
}

此操作對記錄按dep字段值進行分組,並使用firstdepDepmajor使first輸出每個組第一條記錄的dep字段,輸出字段名爲Dep;又將 major字段的值使用addtoset 放入數組中返回,輸出字段名爲addtoset_major,如下:

$count

記錄分組後,用$count 取出分組所包含的總記錄條數。

示例

對記錄分組後,返回表所有的記錄條數:

> db.foo.bar.aggregate({ $group: { Total: { $count: "$dep" } } })
{
  "Total": 1001
}

$first

記錄分組後,取分組中第一條記錄指定的字段值,對嵌套對象使用點操作符(.)引用字段名。

示例

對記錄分組後,輸出每個分組第一條記錄的指定字段值:

> db.foo.bar.aggregate({ $group: { _id: "$dep", Dep: { $first: "$dep" }, Name: { $first: "$info.name" } } })
{
  "Dep": "物電學院",
  "Name": "Lily"
}
{
  "Dep": "計算機學院",
  "Name": "Tom"
}

此操作對記錄按dep字段分組,取每個分組中第一條記錄的dep字段值和嵌套對象name字段值,輸出字段名分別爲 Dep 和 Name。

$avg

記錄分組後,取分組中指定字段的平均值返回,對嵌套對象使用點操作符(.)引用字段名。

示例

對記錄分組後,返回分組中指定字段的平均值:

> db.foo.bar.aggregate({ $group: { _id: "$dep", avg_age: { $avg: "$info.age" }, max_age: { $max: "$info.age" }, min_age: { $min: "$info.age" } } })
{
  "avg_age": 23.727273,
  "max_age": 36,
  "min_age": 15
}
{
  "avg_age": 24.5,
  "max_age": 30,
  "min_age": 20
}

此操作對記錄按dep字段分組,使用avgageavgage使avg返回每個分組中的嵌套對象age字段的平均值,輸出字段名爲avg_age;又使用min返回每個分組中嵌套對象age字段的最小值,輸出字段名爲min_age,使用$max 返回每個分組中嵌套對象 age字段的最大值,輸出字段名爲max_age。

$max

記錄分組後,取分組中指定字段的最大值返回,對嵌套對象使用點操作符(.)引用字段名。

示例

對記錄分組後,返回分組中指定字段的最大值:

> db.foo.bar.aggregate({ $group: { _id: "$dep", max_score: { $max:"$score" }, Name: { $last: "$info.name" } } })
{
  "max_score": 93,
  "Name": "Kate"
}
{
  "max_score": 90,
  "Name": "Jim"
}

此操作對記錄按dep字段分組,使用$max 返回每個分組中score 字段的最大值,輸出字段名爲max_score,又使用 $last取每個分組中最後一條記錄嵌套對象name字段值,輸出字段名爲Name。

$min

記錄分組後,取分組中指定字段的最小值返回,對嵌套對象使用點操作符(.)引用字段名。

示例

對記錄分組後,返回分組中指定字段的最小值:

> db.foo.bar.aggregate({ $group: { _id: "$dep", min_score: { $min: "$score" }, Name: { $last: "$info.name" } } })
{
  "min_score": 72,
  "Name": "Kate"
}
{
  "min_score": 69,
  "Name": "Jim"
}

此操作對記錄按dep字段分組,使用$min 返回每個分組中score字段的最小值,輸出字段名爲min_score,又使用 $last取每個分組中最後一條記錄嵌套對象name字段值,輸出字段名爲Name。

$last

記錄分組後,取分組中最後一條記錄指定的字段值,對嵌套對象使用點操作符(.)引用字段名。

示例

對記錄分組後,輸出每個分組最後一條記錄的指定字段值:

> db.foo.bar.aggregate({ $group: { _id: "$dep", Major: { $addtoset: "$major" }, Name: { $last: "$info.name" } } })
{
  "Major": [
    "物理學",
    "光學",
    "電學"
  ],
  "Name": "Kate"
}
{
  "Major": [
    "計算機科學與技術",
    "計算機軟件與理論",
    "計算機工程"
  ],
  "Name": "Jim"
}

此操作對記錄按dep字段分組,使用lastnameNamemajor使last取每個分組中最後一條記錄嵌套對象name字段值,輸出字段名爲Name,並且將每個分組中的major字段值使用addtoset填充到數組中返回,返回字段名爲Major。

$push

記錄分組後,使用$push將指定字段值添加到數組中,即使數組中已經存在相同的值,也繼續添加。對嵌套對象使用點操作符(.)引用字段名。

示例
> db.foo.bar.aggregate({ $group: { _id: "$dep", Dep: { $first: "$dep" }, push_age: { $push: "$info.age" } } })
{
  "Dep": "物電學院",
  "push_age": [
    28,
    18,
    20,
    30,
    28,
    20
  ]
}
{
  "Dep": "計算機學院",
  "push_age": [
    25,
    20,
    22
  ]
}

此操作對記錄按dep字段值進行分組,每個分組中嵌套對象age字段的值使用$push放入數組中返回,輸出字段名爲 push_age,如下:

$sum

記錄分組後,返回每個分組中指定字段值的總和,對嵌套對象使用點操作符(.)引用字段名。

示例
> db.foo.bar.aggregate({ $group: { _id: "$dep", sum_score: { $sum: "$score" }, Dep: { $first: "$dep" } } })
{
  "sum_score": 888,
  "Dep": "物電學院"
}
{
  "sum_score": 476,
  "Dep": "計算機學院"
}

此操作對記錄按dep字段分組,使用sumscoresumscore使sum返回每個分組中score字段值的總和,輸出字段名爲sum_score;又使用first取每個分組中第一條記錄的dep字段值,輸出字段名爲Dep。

備註(SQL to Aggregate映射表)

下表主要是描述 SQL 關鍵字與 SequoiaDB 聚集操作符的對照表。

SQL關鍵字 SequoiaDB聚集操作符
where $match
group by $group
having 對 $group 後的字段進行 $match
select $project
order by $sort
top 或者 limit $limit
offset $skip

下表主要描述標準SQL語句與SequoiaDB聚集語句之間的對照。

SQL語句 SequoiaDB語句 描述
select product_id as p_id , price from foo.bar db.foo.bar.aggregate({KaTeX parse error: Expected '}', got 'EOF' at end of input: project:{p_id:"product_id",price:1,date:0}}) 返回所有記錄的 product_id 和 price 字段,其中 product_id 重命名爲 p_id,對記錄中的 date 字段不返回。
select sum(price) as total from foo.bar db.foo.bar.aggregate({KaTeX parse error: Expected '}', got 'EOF' at end of input: …id:null,total:{sum:"$price"}}}) 對 table 中的字段 price 值求和,並重命名爲 total。
select product_id, sum(price) as total from foo.bar group by product_id db.foo.bar.aggregate({KaTeX parse error: Expected '}', got 'EOF' at end of input: group:{ _id:"product_id",product_id:{first:&quot;first:&quot;product_id"},total:{sum:&quot;sum:&quot;price"}}}) 對錶 table 中的記錄按 product_id 字段分組;求每個分組中字段 price 值的累加和,並重命名爲 total。
select product_id, sum(price) as total from foo.bar group by product_id order by total db.foo.bar.aggregate({KaTeX parse error: Expected '}', got 'EOF' at end of input: group:{_id:"product_id",product_id:{first:&quot;first:&quot;product_id"},total:{sum:&quot;sum:&quot;price"}}},{$sort:{total:1}}) 對錶 table 中的記錄按 product_id 字段分組;求每個分組中字段 price 值的累加和,並重命名爲 total;對結果集按字段名 total 的值升序排序。
select product_type_id, product_id, sum(price) as total from foo.bar group by product_type_id, product_id db.foo.bar.aggregate({KaTeX parse error: Expected '}', got 'EOF' at end of input: …oduct_type_id:"product_type_id",product_id:“KaTeX parse error: Expected 'EOF', got '}' at position 12: product_id"}̲,product_id:{first:“KaTeX parse error: Expected 'EOF', got '}' at position 12: product_id"}̲,total:{sum:”$price”}}}) 對錶 table 中的記錄按首先按 product_type_id 字段分組,再按 product_id 字段分組;求每個分組中字段 price 值的累加和,並重命名爲 total。
select product_id, sum(price) as total from foo.bar group by product_id having total > 1000 db.foo.bar.aggregate({KaTeX parse error: Expected '}', got 'EOF' at end of input: group:{_id:"product_id",product_id:{first:&quot;first:&quot;product_id"},total:{sum:&quot;sum:&quot;price"}}},{KaTeX parse error: Expected '}', got 'EOF' at end of input: match:{total:{gt:1000}}}) 對錶 table 中的記錄按 product_id 字段分組;求每個分組中字段 price 值的累加和,並重命名爲 total;只返回滿足條件 total 字段值大於1000的分組。
select product_id, sum(price) as total from foo.bar where product_type_id = 1001 group by product_id db.foo.bar.aggregate({KaTeX parse error: Expected 'EOF', got '}' at position 29: …t_type_id:1001}}̲,{group:{_id:“KaTeX parse error: Expected '}', got 'EOF' at end of input: …d",product_id:{first:“KaTeX parse error: Expected 'EOF', got '}' at position 12: product_id"}̲,total:{sum:”$price”}}}) 選擇符合條件 product_type_id = 1001 的記錄;對選出的記錄按 product_id 進行分組;對每個分組中的 price 字段值就和,並重命名爲 total。
select product_id, sum(price) as total from foo.bar where product_type_id = 1001 group by product_id having total > 1000 db.foo.bar.aggregate({KaTeX parse error: Expected 'EOF', got '}' at position 29: …t_type_id:1001}}̲,{group:{_id:"KaTeX parse error: Expected '}', got 'EOF' at end of input: …d",product_id:{first:"KaTeX parse error: Expected 'EOF', got '}' at position 12: product_id"}̲,total:{sum:"KaTeX parse error: Expected 'EOF', got '}' at position 7: price"}̲}},{match:{total:{$gt:1000}}}) 選擇符合條件 product_type_id = 1001 的記錄;對選出的記錄按 product_id 進行分組;對每個分組中的 price 字段值就和,並重命名爲 total;只返回滿足條件 total 字段值大於1000的分組。
select top 10 * from foo.bar db.foo.bar.aggregate({KaTeX parse error: Expected 'EOF', got '}' at position 17: …roup:{_id:null}}̲,{limit:10}) 返回結果集中的前10條記錄。
select * from foo.bar offset 50 rows fetch next 10 db.foo.bar.aggregate({KaTeX parse error: Expected 'EOF', got '}' at position 17: …roup:{_id:null}}̲,{skip:50},{$limit:10}) 跳過結果集中前50條記錄之後,返回接下來的10條記錄。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章