mongodb bson以及bson D中的一些操作参数

原创
2020/03/19 20:06
阅读数 2.6W

上一篇略微写了一下go操作mongodb的curd,其中有一个bson有的人可能不是很熟悉,这里就跟大家稍微的讲讲。

bson是一种类似json的二进制存储形式,它就是mongodb的存储结构,它的数据结构要比json多,如 int, long, date, floating point, and decimal128

我在mongodb官网找到一个blog里面也写了我用的go的mongodb拓展中bson的介绍( https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial ),他是这样写的。

 The Go Driver has two families of types for representing BSON data: The D types and the Raw types.

The D family of types is used to concisely build BSON objects using native Go types. This can be particularly useful for constructing commands passed to MongoDB. The D family consists of four types:

  • D: A BSON document. This type should be used in situations where order matters, such as MongoDB commands.
  • M: An unordered map. It is the same as D, except it does not preserve order.
  • A: A BSON array.
  • E: A single element inside a D.

The Raw family of types is used for validating a slice of bytes. You can also retrieve single elements from Raw types using a Lookup(). This is useful if you don't want the overhead of having to unmarshall the BSON into another type. 

大概意思是:这个mongodb GO版的拓展有两种族来使用bosn数据,一个D还有一个是RAW。

D族是使用原生GO的形式来简单的构造一个BSON对象。这个对于使用命令来操作mongodb是十分有用的。D()由下面4种类型:

D:一个BSON文档,这个类型应该被用在顺序比较重要的场合(言外之意就是有序的),比如说mongodb的命令。

M:一个无序的map。它除了无序之外和D是一样的(可以理解为map和bson是可以转换)。

A:一个BSON形式的数组。

E:一个D里面的单独元素。(就是文档里的一个元素)

RAW族是被用来判断是否为bytes的一个slice。你也可以用look up()方法从RAW取得一个元素。这可以在你将BSON转化为另一个形式的数据时是十分有用的(原文大概意思是可以节省你转化数据时的开销)。

下面简单说下在操作D族时会有使用到一些条件参数。

不等于!=($ne)

c.Find(bson.M{"name": bson.M{"$ne": "Tom"}}).All(&users)

大于>($gt)

c.Find(bson.M{"age": bson.M{"$gt": 10}}).All(&users)

小于<($lt)

c.Find(bson.M{"age": bson.M{"$lt": 10}}).All(&users)

大于等于>=($gte)

c.Find(bson.M{"age": bson.M{"$gte": 10}}).All(&users)

小于等于<=($lte)

c.Find(bson.M{"age": bson.M{"$lte": 10}}).All(&users)

in($in)

c.Find(bson.M{"name": bson.M{"$in": []string{"Tom", "Jerry"}}}).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)

$all查询所有

c.Find(bson.M{"name": bson.M{"$all": []int{10,11,12}}}).All(&users

$or

c.Find(bson.M{"$or": []bson.M{bson.M{"age": 11}, bson.M{"sex": 1}}}).All(&users)

修改$set

增加值$incr

向数组增加一个元素$push

filter := bson.D{{"name", "Speike"}}

update := bson.D{
   {"$push", bson.D{
      {"interests", "sing"},
   }},
}
updateResult, err := collection.UpdateOne(context.TODO(), filter, update)

移除shu'zu一个元素$pull

filter := bson.D{{"name", "Speike"}}

update := bson.D{
   {"$pull", bson.D{
      {"interests", "sing"},
   }},
}
updateResult, err := collection.UpdateOne(context.TODO(), filter, update)
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部