MongoDB $unwind 获取计数
MongoDB 中的 $unwind 会解构输入文档中的数组字段,为每个元素输出一个文档。将 $unwind 与 aggregate() 一起使用以获取计数。我们使用文档创建一个集合 -
> db.demo478.insertOne(
... {
...
... "Details" : {
... _id:1,
... "Information" : [
... {
... "Name" : "Chris",
... "Age":21
... },
... {
... "Name" : "David",
... "Age":23
... },
... {
...
... "Name" : null,
... "Age":22
... },
... {
...
... "Name" : null,
... "Age":24
... }
... ]
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e8204acb0f3fa88e2279092")
}
>
> db.demo478.insertOne(
... {
...
... "Details" : {
... _id:2,
... "Information" : [
... {
... "Name" : "Bob",
... "Age":21
... },
... {
... "Name" : null,
... "Age":20
... }
... ]
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e8204adb0f3fa88e2279093")
}使用 find() 方法,从集合中显示所有文档 -
> db.demo478.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e8204acb0f3fa88e2279092"), "Details" : { "_id" : 1, "Information" : [ {
"Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : null, "Age" : 22 }, {
"Name" : null, "Age" : 24 } ] } }
{ "_id" : ObjectId("5e8204adb0f3fa88e2279093"), "Details" : { "_id" : 2, "Information" : [ {
"Name" : "Bob", "Age" : 21 }, { "Name" : null, "Age" : 20 } ] } }以下是对 $unwind 计算数量的查询 -
> db.demo478.aggregate([
... { "$unwind": "$Details.Information" },
... {
... "$group" : {
... "_id": "$Details.Information.Age",
... "count" : {
... "$sum": {
... "$cond": [
... { "$gt": [ "$Details.Information.Name", null ] },
... 1, 0
... ]
... }
... }
... }
... },
... { "$sort" : { "count" : -1 } }
... ])这将产生以下输出 -
{ "_id" : 21, "count" : 2 }
{ "_id" : 23, "count" : 1 }
{ "_id" : 24, "count" : 0 }
{ "_id" : 20, "count" : 0 }
{ "_id" : 22, "count" : 0 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP