mongo个人收集的一些技巧
1 插入不重复的数据到数组里,并只保留指定数量的数据(数组长度不变)
查了一圈,最后在stackoverflow找到的解决办法。。我太菜了没想到这么简单的方法
mongo更新数组数据有$push
和$addToSet
,
$push
支持多种运算符但是不会对插入的数据自动筛选,数组里会插入重复值;
$addToSet
不会插入重复值,但是不支持很多运算符,包括$slice
,所以没法指定插入后的数组长度
数据库内容:{"insert":"this","a":[111,666,777,888]}
-----------------------------------------------------------
push:
db.collection.update(
{ "insert":"this" },
{ "$push": { "a": {
"$each": [111,222,333], //插入数组内所有数据
"$position":0, //指定插入位置
"$sort":1 //对插入后的数据排序,1升序 -1降序
"$slice":5 //插入后的数组只保留5个数据;5是保留数组前面5个,保留后5个可以用-5
}
}
)
结果:{"insert":"this","a":[111,111,222,333,666]} //有重复数据
------------------------------------------------------------
addToSet:
db.collection.update(
{ "insert":"this" },
{ "$addToSet": { "a": { "$each": [111,222,333]} } //addToSet只能用$each,所以没法保留指定长度的数组
)
结果:{"insert":"this","a":[111,222,333,666,777,888]} //无重复但是不能限制长度
使用$ne
(not equal)运算符可以先判定a是否有111,再进行插入操作,缺点就是$each
没法直接接数组,需要自己写个循环遍历要插入的数据
python代码:
for i in [111,222,333]:
db.test.update_one(
{"$and": [{"insert": "this"}, {"a": {"$ne": i}}]},
{
"$push": {
"a": {"$each": [i], "$position": 0, "$sort": 1, "$slice": 5}
}
},
)
结果:{"insert" : "this", "a" : [ 111, 222, 333, 666, 777 ]} //111没有插入
2 获取重复数据
db.table_name.aggregate( {'$group':{
'_id': {'字段名': '$字段名'},
'uniqueIds': {'$addToSet': '$_id'},
'count' : {'$sum': 1}
}},
{'$match': {
'count': {'$gt': 1}
}})