MongoDB(Golang)常用复合查询
MongoDB(Golang)查询&修改
https://www.jianshu.com/p/b63e5cfa4ce5
>> 资源下载: https://72k.us/file/14896800-396374653
以下所有例子中结构定义如下:
type User struct {Id_ bson.ObjectId `bson:"_id"`Name string `bson:"name"`Age int `bson:"age"`JoinedAt time.Time `bson:"joined_at"`Interests []string `bson:"interests"
}
1、查询
通过func (c *Collection) Find(query interface{}) *Query
来进行查询,返回的Query struct可以有附加各种条件来进行过滤。
通过Query.All()
可以获得所有结果,通过Query.One()
可以获得一个结果,注意如果没有数据或者数量超过一个,One()会报错。
条件用bson.M{key: value}
,注意key必须用MongoDB中的字段名,而不是struct的字段名。
1.1、查询所有
var users []User
c.Find(nil).All(&users)
上面代码可以把所有Users都查出来:
1.2、根据ObjectId查询
id := "5204af979955496907000001"
objectId := bson.ObjectIdHex(id)
user := new(User)
c.Find(bson.M{"_id": objectId}).One(&user)
更简单的方式是直接用FindId()方法:
c.FindId(objectId).One(&user)
注意这里没有处理err。当找不到的时候用One()方法会出错。
1.3、单条件查询
=($eq)
c.Find(bson.M{"name": "Jimmy Kuu"}).All(&users)
!=($ne)
c.Find(bson.M{"name": bson.M{"$ne": "Jimmy Kuu"}}).All(&users)
>($gt)
c.Find(bson.M{"age": bson.M{"$gt": 32}}).All(&users)
<($lt)
c.Find(bson.M{"age": bson.M{"$lt": 32}}).All(&users)
>=($gte)
c.Find(bson.M{"age": bson.M{"$gte": 33}}).All(&users)
<=($lte)
c.Find(bson.M{"age": bson.M{"$lte": 31}}).All(&users)
in($in)
c.Find(bson.M{"name": bson.M{"$in": []string{"Jimmy Kuu", "Tracy Yu"}}}).All(&users)
no in($nin)
同$in,
是否包含这个键($exists)
c.Find(bson.M{"name": bson.M{"$exists": true}}).All(&users)
查询键值为null的字段
c.Find(bson.M{"name": bson.M{"$in":[]interface{}{null}, "$exists": true}}).All(&users)
模糊查询($regex)
c.Find(bson.M{"name": bson.M{"$regex": "^[0-9]+"}}).All(&users)
$size
查询键值为长度是size的数组
c.Find(bson.M{"Interests": bson.M{"$size": 3}}).All(&users)
上面就是查询Interests数组长度为3的所有人
$all
查询数组中包含所有值得匹配(不分顺序,只看包含与否)
c.Find(bson.M{"Interests": bson.M{"$all": []string{"11","22","33"}}}).All(&users)
上面就是查询Interests中包含11,22,33的所有人
如果数组只有一项内容
c.Find(bson.M{"Interests": bson.M{"$all": []string{"11"}}}).All(&users)
c.Find(bson.M{"Interests": "11"}).All(&users)
以上结果一致
key.index
如果要查询数组指定位置
c.Find(bson.M{"Interests.2": "33"}).All(&users)
以上就是查询Interests的第二个元素为"33"的所有人
1.4、多条件查询
and($and)
c.Find(bson.M{"name": "Jimmy Kuu", "age": 33}).All(&users)
or($or)
c.Find(bson.M{"$or": []bson.M{bson.M{"name": "Jimmy Kuu"}, bson.M{"age": 31}}}).All(&users)
2、修改
通过func (*Collection) Update来进行修改操作。
func (c *Collection) Update(selector interface{}, change interface{}) error
注意修改单个或多个字段需要通过$set操作符号,否则集合会被替换。
2.1、($set)
修改字段的值
c.Update(
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
bson.M{"$set": bson.M{ "name": "Jimmy Gu", "age": 34, }}
)
2.2、inc($inc)
字段增加值
c.Update(
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
bson.M{"$inc": bson.M{ "age": -1, }}
)
2.3、push($push)
从数组中增加一个元素
c.Update(
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
bson.M{"$push": bson.M{ "interests": "Golang", }}
)
2.4、pull($pull)
从数组中删除一个元素
c.Update(
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
bson.M{"$pull": bson.M{ "interests": "Golang", }}
)
2.5、删除
c.Remove(bson.M{"name": "Jimmy Kuu"})
这里也支持多条件,参考多条件查询。
golang 使用mongo-go-dirver创建TTL索引, 过期自动删除数据
sky_terra
本文链接:https://blog.csdn.net/sky_terra/article/details/88357065
数据库:test_db, 数据表 test_table:
id |
content |
expire_date |
---|---|---|
1 | Good luck |
2019-03-01 08:14:58.000 |
2 | Good luck |
2019-03-02 08:14:58.000 |
3 | Good luck |
2019-03-03 08:14:58.000 |
4 | Good luck |
2019-03-04 08:14:58.000 |
5 | Good luck |
2019-03-05 08:14:58.000 |
6 | Good luck |
2019-03-06 08:14:58.000 |
示例代码:
client = mongo.Connect(...)
// mongo-go-driver v0.1.0 使用如下代码
indexModel := mongo.IndexModel{
Keys: bsonx.Doc{{"expire_date", bsonx.Int32(1)}}, // 设置TTL索引列"expire_date"
Options:mongo.NewIndexOptionsBuilder().ExpireAfterSeconds((1*24*3600)).Build(), // 设置过期时间1天,即,条目过期一天过自动删除
}
// mongo-go-driver v0.3.0 使用如下代码
indexModel := mongo.IndexModel{
Keys: bsonx.Doc{{"expire_date", bsonx.Int32(1)}}, // 设置TTL索引列"expire_date"
Options:options.Index().SetExpireAfterSeconds(1*24*3600), // 设置过期时间1天,即,条目过期一天过自动删除
}
_, err := client.Database("test_db").Collection("test_table").Indexes().CreateOne(context.Background(), indexModel) // 创建TTL
if err != nil {
// 出错处理
}
如果当前时间2019-03-02 08:15:58.000,则第一条记录就会被自动删除
>> 菜鸟教程: https://www.runoob.com/mongodb/mongodb-aggregate.html
MongoDB 聚合
MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。有点类似sql语句中的 count(*)。
aggregate() 方法
MongoDB中聚合的方法使用aggregate()。
语法
aggregate() 方法的基本语法格式如下所示:
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
实例
集合中的数据如下:
{_id: ObjectId(7df78ad8902c)title: 'MongoDB Overview', description: 'MongoDB is no sql database',by_user: 'runoob.com',url: 'http://www.runoob.com',tags: ['mongodb', 'database', 'NoSQL'],likes: 100 }, {_id: ObjectId(7df78ad8902d)title: 'NoSQL Overview', description: 'No sql database is very fast',by_user: 'runoob.com',url: 'http://www.runoob.com',tags: ['mongodb', 'database', 'NoSQL'],likes: 10 }, {_id: ObjectId(7df78ad8902e)title: 'Neo4j Overview', description: 'Neo4j is no sql database',by_user: 'Neo4j',url: 'http://www.neo4j.com',tags: ['neo4j', 'database', 'NoSQL'],likes: 750 },
现在我们通过以上集合计算每个作者所写的文章数,使用aggregate()计算结果如下:
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}]) {"result" : [{"_id" : "runoob.com","num_tutorial" : 2},{"_id" : "Neo4j","num_tutorial" : 1}],"ok" : 1 } >
以上实例类似sql语句:
select by_user, count(*) from mycol group by by_user
在上面的例子中,我们通过字段 by_user 字段对数据进行分组,并计算 by_user 字段相同值的总和。
下表展示了一些聚合的表达式:
表达式 | 描述 | 实例 |
---|---|---|
$sum | 计算总和。 | db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}]) |
$avg | 计算平均值 | db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}]) |
$min | 获取集合中所有文档对应值得最小值。 | db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}]) |
$max | 获取集合中所有文档对应值得最大值。 | db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}]) |
$push | 在结果文档中插入值到一个数组中。 | db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}]) |
$addToSet | 在结果文档中插入值到一个数组中,但不创建副本。 | db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}]) |
$first | 根据资源文档的排序获取第一个文档数据。 | db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}]) |
$last | 根据资源文档的排序获取最后一个文档数据 | db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}]) |
管道的概念
管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数。
MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。
表达式:处理输入文档并输出。表达式是无状态的,只能用于计算当前聚合管道的文档,不能处理其它的文档。
这里我们介绍一下聚合框架中常用的几个操作:
- $project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。
- $match:用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。
- $limit:用来限制MongoDB聚合管道返回的文档数。
- $skip:在聚合管道中跳过指定数量的文档,并返回余下的文档。
- $unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
- $group:将集合中的文档分组,可用于统计结果。
- $sort:将输入文档排序后输出。
- $geoNear:输出接近某一地理位置的有序文档。
管道操作符实例
1、$project实例
db.article.aggregate({ $project : {title : 1 ,author : 1 ,}});
这样的话结果中就只还有_id,tilte和author三个字段了,默认情况下_id字段是被包含的,如果要想不包含_id话可以这样:
db.article.aggregate({ $project : {_id : 0 ,title : 1 ,author : 1}});
2.$match实例
db.articles.aggregate( [{ $match : { score : { $gt : 70, $lte : 90 } } },{ $group: { _id: null, count: { $sum: 1 } } }] );
$match用于获取分数大于70小于或等于90记录,然后将符合条件的记录送到下一阶段$group管道操作符进行处理。
3.$skip实例
db.article.aggregate({ $skip : 5 });
经过$skip管道操作符处理后,前五个文档被"过滤"掉。
Ref:
https://docs.mongodb.com/manual/core/index-ttl/ TTL index详细介绍
https://docs.mongodb.com/manual/indexes/#index-types IndexModel中关于index type的详细介绍
MongoDB(Golang)常用复合查询相关推荐
- golang常用库之-mgo.v2包、MongoDB官方go-mongo-driver包、七牛Qmgo包 | go操作mongodb、mongodb bson
文章目录 golang常用库之-mgo.v2包.MongoDB官方go-mongo-driver包.七牛Qmgo包 | go操作mongodb.mongodb bson 一.[不推荐]mgo.v2包 ...
- SpringBoot增和MongoDB实现增删改查、复合查询
SpringBoot增和MongoDB实现增删改查.复合查询 依赖 <dependency><groupId>org.springframework.boot</grou ...
- MongoDB 教程三: 高级查询 (SQL到MongoDB映射表)
查询接口 对于查询操作,MongoDB 提供了 db.collection.find() 方法.这个方法接收查询条件和映射两个条件并且返回一个指向匹配文档的 游标 .你可以使用 limits, ski ...
- mysql select符合查询_数据库select group by 和having语句 多表连接查询 复合查询
1.SELECT --group by 子句 group by子句按照指定的列column_name对表数据进行分组 group by 后面跟的列也叫分组特性列 使用group by后,能选择的列 ...
- mongoDB的常用语法
安装: 到mongodb官网下载安装包或者压缩包:https://www.mongodb.com/download-center?jmp=nav 1.如果是msi包的话则点击按步骤安装,如果是压缩包的 ...
- MongoDB实战系列之二:MongoDB的常用操作
#以服务方式启动mongodb,要求验证 /elain/apps/mongodb/bin/mongod --fork --port 27001 --auth --dbpath /elain/data/ ...
- 总结MongoDB采用MongoRepository进行查询
Java操作MongoDB采用MongoRepository进行条件查询 1) 实体类实现Serializable接口 @Document(collection = "Memo" ...
- Hibernate的几种查询方式 HQL,QBC,QBE,离线查询,复合查询,分页查询
HQL查询方式 这一种我最常用,也是最喜欢用的,因为它写起来灵活直观,而且与所熟悉的SQL的语法差不太多.条件查询.分页查询.连接查询.嵌套查询,写起来与SQL语法基本一致,唯一不同的就是把表名换成了 ...
- mongodb中常用的shell命令
mongodb中常用的shell命令 常用的shell命令 1.帮助命令 2.数据库操作命令 3.创建数据库和集合 4.集合中的文档(document)操作 5.聚集集合查询 常用的shell命令 1 ...
最新文章
- java观察者模式类图_设计模式(十八)——观察者模式(JDK Observable源码分析)...
- 【Python金融量化 6- 100 】、六、蒙特卡洛预测微软股票
- 最新报告:我国博士研究生累计招生已近150万!延毕率逐年上升
- Design Compiler指南——设计综合过程
- css新奇技术及其未来发展
- java.lang.IllegalArgumentException: Could not resolve placeholder ‘stu.age‘ in value “${stu.age}
- 新浪微博登陆以及发送微博(附python源码)
- 【报告分享】中国创新生态发展报告2019-德勤.pdf
- 山东春季高考计算机知识点,山东春季高考专业知识点总结
- 在linux命令行利用SecureCRT上传下载文件
- bufferedreader读取中文乱码_Python OpenCV与中文相关的三个常见问题
- 欠拟合、过拟合、优化器
- 【首发】'k4' 宏病毒专杀 原创新型excel宏病毒专杀工具
- 群体智能算法之蝙蝠算法
- PropertyUtils 工具类
- x264码率控制-帧duration计算
- UML之教学管理系统——4、Rational Rose画活动图
- 开始学 ruby on rails
- 数据禾|全国10米DEM数字高程数据
- 阿里巴巴国际站如何发布高质量的产品?