mongodb 常用语法 & 踩坑记录

220 阅读1分钟

常用语法

常用操作符

汇总表

操作符使用方式 & 例子
distinctdb.collection.distinct(字段,查询,选项)
or & and
$eq (equal) 等于
$ne (not equal) 不等于
$not字段值不匹配表达式 或 字段值不存在 , 相当于 not like
相当于like 匹配db.user.find({name: /A/})
$sortdb.collection.find().sort({KEY:1}) 1 为升序排列 -1 是用于降序排列
$gt(greater than) 大于
$gte(greater than equal)
大于等于
$lt(less than) 小于
$lte(less than equal) 小于等于
$in等于数组中某一项
$nin(not in)
不等于数组中的任何一项

distinct

db.resource.distinct(
  "type"
)

db.resource.distinct(
  "type", 
  {
  	"name": "test_name"
  },
)

or & and

db.resource.find({
    '$or': [
        {"region": ""},
        {"region": null},
    ],
    '$and': [
        {"name": "test1"}
    ]
})

$ne

db.user.find({name: {$ne: "A"}})

not like

db.users.find({ name: { $not: /^A/ } })
$not操作符用于排除匹配正则表达式/^A/的数据
/^A/表示字符串以’A’开头

另一种相同效果的写法
db.users.find({ name: { $not: /A.*/ } })

like 匹配

匹配包含 A 的所有集合数据
db.user.find({name: /A/})

符号:/A$/(右匹配)
说明:匹配以 A 结束的所有集合数据
db.user.find({name: /A$/})

符号:/^A/ (左匹配)
说明:匹配以 A 开始的所有集合数据
db.user.find({name: /^A/})

$sort

db.collection.find().sort({field:1})

  • 1 为升序排列

  • -1 是用于降序排列

db.service.find({'name': "A"}).
sort({'created': -1}).limit(100);

upsert语法

设置options.Update().SetUpsert(true)

func CreateResource(ctx context.Context) error {
	coll := getMongoClient(ctx).Database("database_name").Context(ctx).Collection("test_coll")

	// create resource if it does not exist or update when it is not deleted
	filter := bson.D{{Key: "uniq_id", Value: 11111}}
	doc := bson.D{
		{"$set", bson.D{
			{Key: "name", Value: "abc_name"}
		}},

		{"$setOnInsert", bson.D{
  	  {Key: "uniq_id", Value: 11111}
			{Key: "created_at", Value: 12345}
		}},
	}

	opts := options.Update().SetUpsert(true)
	_, err = coll.UpdateOne(ctx, filter, doc, opts)
	return err
}

group by + order by 语法

select source_err_str, count(1) as cnt from sync_log 
where table_name = 'service_infos' 
group by source_err_str 
order by cnt desc;

db.sync_log.aggregate([
    {
        '$match' : {
  				'table_name': "service_infos", 
  			},
    },
    {
        '$group' : {'_id' : "$source_err_str", "cnt" : {'$sum' : 1}}
    },
    {
        '$sort' : {'cnt': -1}
    }
])

踩坑系列

bson.M是无序的,需要使用bson.D

  • 千万不要在 group或sort中使用 bson.M
  • 下面是正确的使用方式
{
    Key: "$sort", 
    Value: bson.D{
        {
            "field_1": 1
        },
        {
            "field_2": -1
        },
    },
},

mongo的集合默认是区分大小写的 且不可更改

  • mysql默认不区分大小写

可以在创建集合的时候,指定collation如下,代表不区分大小写

db.createCollection(
    "catalog",
    {
        "collation": {"locale": "en", "strength": 2}
    }
)

使用默认的 _id主键做大小比较的分页查询时,会少数据

后插入的数据,_id可能比已有的 _id小(涉及到_id的生成规则)
如果查询的时候 插入了一个数据,那这个数据就查不出来了,必须下一次才可以查到