mongodbproject的简单介绍

本篇文章给大家谈谈mongodbproject,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

mongodb查询实例

类似MySQL的select * from EVI_EGZ_GEAR_DAY where quantity0=27

类似MySQL的select * from EVI_EGZ_GEAR_DAY where lastModify"2020-07-02T16:08:45+08:00"

db.EVI_BIZ_DAYINFO.find({"ReportDay":{$gte:20200601 ,$lte: 20200630},"LoginID":"304095318","Is_Statistics":1})

操作 格式 范例 RDBMS中的类似语句

等于 {铅让key:value} db.col.find({"by":"菜鸟教程"}).pretty() where by = '菜鸟教程'

小于 {key:{$lt:value}} db.col.find({"likes":{$lt:50}}).pretty() where likes 50

小于或等于 {key:{$lte:value}} db.col.find({"likes":{$lte:50}}).pretty() where likes = 50

大于 {key:{$gt:value}} db.col.find({"likes":{$gt:50}}).pretty() where likes 50

大于或等于 {key:{$gte:value}} db.col.find({"likes":{$gte:50}}).pretty() where likes = 50

不等于 {key:{$ne:value}} db.col.find({"likes":{$ne:50}}).pretty() where likes != 50

类似MySQL的select loginId from EVI_EGZ_GEAR_DAY group by loginId

类似MySQL的select loginId,count(*) from EVI_EGZ_GEAR_DAY where loginId=100870655 group by loginId

5.db.EVI_RPT_MARKETMON_ANALYSIS.find({"reportTime":"201810","areaParentCode":"430000","machineCode":"MT0000000212","machineType":"2","nationCode":"CN","calcType":"0"},

{"areaName":1,"machineName":1,"workTime":1,"equCount":1,"workCount":1,"restCount":1,"highWorkCount":1,"avgWorkTime":1,"workRate":1,"calcType":"1"}).sort({ equCount:-1 })

db.EVI_BIZ_DAYINFO.aggregate([{

                        "$match": {

                            "ReportTime" : ISODate("2020-07-01T00:00:00.000+08:00"),

                            "Is_Statistics": 1,

                            "IsOnline": 1,

                            "MachineType_Code1" : "MT0000000276"// 按照一级槐桥局机型分类统计,否则查询不到数据

   消岩                       }

                    },

                    {

                        "$group" : {

                            _id:{

                            countyCode :"$County_Code", 

                            cityCode :"$City_Code",

                            provinceCode :"$Province_Code", 

                            machineType1 :"$MachineType_Code1",

                            machineType2 :"$MachineType_Code2",

                            nationCode:"$Nation_Code"

                            },

                            highWorkCount : {$sum: { $cond: [ {$gte: [ "$WorkTime",8] },

                                    1,

                                    0 ] }},

                            countWork: {

                                $sum: '$IsWork'

                            },

                            workTime:  {

                                $sum: '$WorkTime'

                            },

                            equCount:{

                                $sum: 1

                            }

                        }

                    }

                ])

db.EVI_BIZ_DAYINFO.find({"ReportDay":20200201,"LoginID":"302060888"})

db.EVI_BIZ_DAYINFO.aggregate([{

                        "$match": {"LoginID":"101065868",

                                    "ReportDay":{$gte: 20200701,$lte:20200731}

                        }

                    },

                    {

                        "$group": {

                            _id:{

                                LoginID:"$LoginID",

                                ReportDay:"$ReportDay"

                            },

                            },

                        WorkTimes:{

                            $sum: "$WorkTime"

                        },

                        totalDay:{

                            $sum: {$cond: [  { $gt: ["$WorkTime",0]},  1,  0 ]}

                        }

                        }

                    },

                    {"$match": {WorkTimes:{$gt:0}}}

])

db.EVI_ALARM_FLEET.update({"reportTime":ISODate("2020-08-21T00:00:00.000+08:00")},{$set:{"reportTime":ISODate("2020-08-22T00:00:00.000+08:00")}},false,true)

db.EVI_ALARM_FLEET.update({"reportTime":ISODate("2020-08-21T00:00:00.000+08:00")},{$set:{"reportTime":ISODate("2020-08-22T00:00:00.000+08:00")}})

db.EVI_BIZ_DAYINFO.find({$or:[{"LoginID":"104259298"},{"LoginID":"132349918"}]})

db.configuration.find({"envType":"hxevi.test","key":{$regex:/mail/}})

相当于MySQL的select * from configuration where envType='hxevi.test' and key like '%mail%'

db.EVI_BIZ_DAYINFO.aggregate([

        {

            "$match": {

                "ReportTime":{"$gte":ISODate("2021-01-18T00:00:00.000+08:00"),"$lte":ISODate("2021-01-24T00:00:00.000+08:00")},

                "Is_Statistics": 1,

                "LoginID": "101102108"

            }

        },

        {"$sort": {"ReportTime": -1}},

        {

            "$group": {

                "_id": "$LoginID",

                "WorkTime": {

                    "$sum": "$WorkTime"

                },

                "IdleTime": {

                    "$sum": "$IdleTime"

                },

                "FuelConsume": {

                    "$sum": "$FuelConsume"

                },

                "IdleFuelConsume": {

                    "$sum": "$IdleFuelConsume"

                },

                "ReportTime": {"$first": "$ReportTime"},

                "City_Code": {"$first": "$City_Code"},

                "City_Name": {"$first": "$City_Name"},

                "County_Code": {"$first": "$County_Code"},

                "County_Name": {"$first": "$County_Name"},

                "Nation_Code": {"$first": "$Nation_Code"},

                "Nation_Name": {"$first": "$Nation_Name"},

                "Province_Code": {"$first": "$Province_Code"},

                "Province_Name": {"$first": "$Province_Name"},

                "Latitude": {"$first": "$Latitude"},

                "Longitude": {"$first": "$Longitude"},

                "TotalIdleFC": {"$first": "$TotalIdleFC"},

                "TotalIdleTime": {"$first": "$TotalIdleTime"},

                "TotalWorkTime": {"$first": "$TotalWorkTime"},

                "TotalFC": {"$first": "$TotalFC"},

                "DataVersion": {"$addToSet": '$DataVersion'},

                "Machine_Model": {"$addToSet": '$Machine_Model'},

                "MachineType_Code1": {"$addToSet": '$MachineType_Code1'},

                "MachineType_Code2": {"$addToSet": '$MachineType_Code2'},

                "MachineType_Code3": {"$addToSet": '$MachineType_Code3'},

                "MachineType_Name1": {"$addToSet": '$MachineType_Name1'},

                "MachineType_Name2": {"$addToSet": '$MachineType_Name2'},

                "MachineType_Name3": {"$addToSet": '$MachineType_Name3'},

                "Serialno": {"$addToSet": '$Serialno'},

                "Customer_Code": {"$addToSet": '$Customer_Code'},

                "Customer_Name": {"$addToSet": '$Customer_Name'},

                "Customer_Tel": {"$addToSet": '$Customer_Tel'},

                "SaleDealer": {"$addToSet": '$SaleDealer'},

                "SaleDealer_Code": {"$addToSet": '$SaleDealer_Code'},

                "SvrDealer": {"$addToSet": '$SvrDealer'},

                "SvrDealer_Code": {"$addToSet": '$SvrDealer_Code'},

                "Register_Date": {"$addToSet": '$Register_Date'},

                "sumIsOnline": {"$sum": '$IsOnline'}

            }

        },

        {

            "$project":{

                "LoginID":"$_id",

                "WorkTime":"$WorkTime",

                "IdleTime":"$IdleTime",

                "FuelConsume":"$FuelConsume",

                "IdleFuelConsume":"$IdleFuelConsume",

                "City_Code":"$City_Code",

                "City_Name": "$City_Name",

                "County_Code": "$County_Code",

                "County_Name": "$County_Name",

                "Nation_Code": "$Nation_Code",

                "Nation_Name": "$Nation_Name",

                "Province_Code": "$Province_Code",

                "Province_Name": "$Province_Name",

                "Latitude": "$Latitude",

                "Longitude": "$Longitude",

                "TotalIdleFC": "$TotalIdleFC",

                "TotalIdleTime": "$TotalIdleTime",

                "TotalWorkTime": "$TotalWorkTime",

                "TotalFC": "$TotalFC",

                "DataVersion": {"$arrayElemAt":["$DataVersion",0]},

                "Machine_Model": {"$arrayElemAt":["$Machine_Model",0]},

                "MachineType_Code1": {"$arrayElemAt":["$MachineType_Code1",0]},

                "MachineType_Code2": {"$arrayElemAt":["$MachineType_Code2",0]},

                "MachineType_Code3": {"$arrayElemAt":["$MachineType_Code3",0]},

                "MachineType_Name1": {"$arrayElemAt":["$MachineType_Name1",0]},

                "MachineType_Name2": {"$arrayElemAt":["$MachineType_Name2",0]},

                "MachineType_Name3": {"$arrayElemAt":["$MachineType_Name3",0]},

                "Serialno": {"$arrayElemAt":["$Serialno",0]},

                "Customer_Code": {"$arrayElemAt":["$Customer_Code",0]},

                "Customer_Name": {"$arrayElemAt":["$Customer_Name",0]},

                "Customer_Tel": {"$arrayElemAt":["$Customer_Tel",0]},

                "SaleDealer": {"$arrayElemAt":["$SaleDealer",0]},

                "SaleDealer_Code": {"$arrayElemAt":["$SaleDealer_Code",0]},

                "SvrDealer": {"$arrayElemAt":["$SvrDealer",0]},

                "SvrDealer_Code": {"$arrayElemAt":["$SvrDealer_Code",0]},

                "Register_Date": {"$arrayElemAt":["$Register_Date",0]},

                "IsOnline": {"$cond": {

                    "if":{"$gt":["$sumIsOnline",0]},"then":1,

                    "else":0

                }}

            }

        }],

    { allowDiskUse: true }).pretty()

[img]

MongoDB中聚合的方法使用aggregate()返回的列表中没有$project里面的属性字段,本人初学,请大家指导一下

去掉project看看原始数据有没有查出字段念芹;如果是用对象接收滚世的,大高肢你需要看看你的对象里定义这个字段没有;

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

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

mongodb Aggregation聚合操作之$project

在上一篇 mongodb Aggregation聚合操作之addFields添加新字段 中详细介绍了mongodb聚合操作中的addFields使用以及参数细节。本篇将开始介绍Aggregation聚合操作中的project 展示字段操作。

说明:

将文档和所请求的字段传递到管道中的下一个阶段。指定的字段可以是输入文档中的现有字段,也可以是新计算的字段。$project接受一个文档,该文档可以指定包含字段、抑制_id字段、添加新字段和重置现有字段的值。或者,您可以指定字段的排除。

语法:

{ $project: { specification(s) } }

初始化数据:

db.books.insertMany([{

  "_id" : 1,

  title: "abc123",

  isbn: "0001122223334",

  author: { last: "zzz", first: "aaa" },

  copies: 5,

  lastModified: "2016-07-28"

},

{

  "_id" : 2,

  title: "Baked Goods",

  isbn: "9999999999999",

  author: { last: "xyz", first: "abc", middle: "" },

  copies: 2,

  lastModified: "2017-07-21"

},

{

  "_id" : 3,

  title: "Ice Cream Cakes",

  isbn: "8888888888888",

  author: { last: "xyz", first: "abc", middle: "mmm" },

  copies: 5,

  lastModified: "2017-07-22"

}])

示例:

1.显示books集合中的title和author字段和id字段,其他字段不展示

db.books.aggregate( [ { $project : { title : 1 , author : 1 } } ] )

2.显示books集合中的title和author字段,其他字段不展示

db.books.aggregate( [ { $project : { _id: 0, title : 1 , author : 1 } } ] )

有条件地排除字段:从MongoDB 3.6开始,您可以在聚合表达式中使用变量REMOVE来有条件地抑制一个字段。

3.下面的$project阶段使用REMOVE变量来排除author.middle字段等于""记录:,如果该字段value值是"",那么该字段不做展示

db.books.aggregate( [

   {

      $project: {

         title: 1,

         "author.first": 1,

         "author.last" : 1,

         "author.middle": {

            $cond: {

               if: { $eq: [ "", "$author.middle" ] },

               then: "$$REMOVE",

               else: "$author.middle"

            }

         }

      }

   }

] )

结果:

{

    "_id" : 1.0,

    "title" : "abc123",

    "author" : {

        "last" : "zzz",

        "first" : "aaa"

    }

}

{

    "_id" : 2.0,

    "title" : "Baked Goods",

    "author" : {

        "last" : "xyz",

        "first" : "abc"

    }

}

{

    "_id" : 3.0,

    "title" : "Ice Cream Cakes",

    "author" : {

        "last" : "xyz",

        "first" : "abc",

        "middle" : "mmm"

    }

}

4.包括计算字段

初始化数据:

db.test.insert({

  "_id" : 1,

  title: "abc123",

  isbn: "0001122223334",

  author: { last: "zzz", first: "aaa" },

  copies: 5

})

下面的$project阶段添加了新的字段isbn、lastName和copiesSold:

db.test.aggregate(

   [

      {

         $project: {

            title: 1,

            isbn: {

               prefix: { $substr: [ "$isbn", 0, 3 ] },

               group: { $substr: [ "$isbn", 3, 2 ] },

               publisher: { $substr: [ "$isbn", 5, 4 ] },

               title: { $substr: [ "$isbn", 9, 3 ] },

               checkDigit: { $substr: [ "$isbn", 12, 1] }

            },

            lastName: "$author.last",

            copiesSold: "$copies"

         }

      }

   ]

)

结果:

{

    "_id" : 1.0,

    "title" : "abc123",

    "isbn" : {

        "prefix" : "000",

        "group" : "11",

        "publisher" : "2222",

        "title" : "333",

        "checkDigit" : "4"

    },

    "lastName" : "zzz",

    "copiesSold" : 5.0

5.项目新数组字段

初始化数据:db.test1.insert({ "_id" : ObjectId("55ad167f320c6be244eb3b95"), "x" : 1, "y" : 1 })

示例:

db.test1.aggregate( [ { $project: { myArray: [ "$x", "$y" ] } } ] )

结果:

{

    "_id" : ObjectId("55ad167f320c6be244eb3b95"),

    "myArray" : [

        1.0,

        1.0

    ]

}

mongoDB表与表的关系及聚合管道查询

MongoDB 中的关系可以是:

MongoDB 聚合管道(Aggregation Pipeline)

使用聚合管道可以对集合中的文档进行变换和组合。

管道操作符

$project 修改文档的结构,可以用来重命名、增加或删除文档中的谈羡字段。

$match 用于过滤文档。用法类似于 find() 方法中的参数。

$limit 用来限制MongoDB聚合管道返回的文档数

$skip 在聚合管羡侍祥道中跳过指定数量的文档,并返回余下的文档。兄搏

$sort 将输入文档排序后输出

$group 将集合中的文档进行分组,可用于统计结果

$lookup 可以引用其他集合的数据(表关联查询)

创建数据

MongoDB开发之 管道操作符

获取MongoDB存储的数据,往往不是直接提取出来就可以使用的,需要对数据进行处理和分析后才可以使用。MongoDB提供了三种执行聚合的方式:聚合管道,map-reduce 函数和单一目的聚合方法悄毕斗。

其中每个'{}'标识一个阶段。

用于过滤数据,只输出符合条件的文档,SQL Example:

MongoDB Example:

将集合中的文档分组,可用于统计结果,SQL Example:

即将machineId进行分组后,对price进行求和。

修改输入文档的结构,限定结果集合,SQL Example:

MongoDB Example:

MongoDB Example:

MongoDB 聚合运算符还有很多,这里只对常用的做了简单的描述,具体的可以参照下表:

聚合管道操作有如:分组( project)、排序( count)等,每个操作在管道中叫做阶段(stage),每个阶段执行的结果会给下一个阶段。

如图:

../images/map-reduce.bakedsvg.svg

其类似Linux中的管道操作:

分四步:数姿

上面示例分为三步:

查询结果为:

MongoDB Documentation aggregation

MongoDB权威指南启磨

关于mongodbproject和的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

标签列表