参考 链接 请查看 有些写的很好
db.comment.createIndex({"field":1},{"name":"news_hash_id_1"})
mongo数据类型转换 str => int 参考
db.article.find({"pv":{"$exists":true}}).forEach(function(x){x.pv = NumberInt(x.pv); db.article.save(x)});
$unwind 数组展开 参考
{ "_id" : ObjectId("5d24370af5242d530f1e5768"), "name" : [ "杨哥", "张哥", "刘哥", "王哥" ], "address" : "北京市朝阳区", "pv" : 200 }
> db.author_test.aggregate([{"$unwind":"$name"}])
{ "_id" : ObjectId("5d24370af5242d530f1e5768"), "name" : "杨哥", "address" : "北京市朝阳区", "pv" : 200 }
{ "_id" : ObjectId("5d24370af5242d530f1e5768"), "name" : "张哥", "address" : "北京市朝阳区", "pv" : 200 }
{ "_id" : ObjectId("5d24370af5242d530f1e5768"), "name" : "刘哥", "address" : "北京市朝阳区", "pv" : 200 }
{ "_id" : ObjectId("5d24370af5242d530f1e5768"), "name" : "王哥", "address" : "北京市朝阳区", "pv" : 200 }
聚合获取数长度的方法 参考
db.test.insert({username:"Alex", tags: ['C#', 'Java', 'C++'] });
db.test.aggregate(
{$match: {username : "Alex"}},
{$unwind: "$tags"},
{$project: {count:{$add:1}}},
{$group: {_id: null, number: {$sum: "$count" }}}
);
{ "result" : [ { "_id" : null, "number" : 3 } ], "ok" : 1 }
db.author_test.aggregate({"$unwind":"$name"},{"$project":{"count":{"$add":1}}},{"$group":{"_id":"null","number":{"$sum":"$count"}}});
group
{ "_id" : ObjectId("5d24370af5242d530f1e5768"), "name" : [ "杨哥", "张哥", "刘哥", "王哥" ], "address" : "北京市朝阳区", "pv" : 200 }
{ "_id" : ObjectId("5d243da2f5242d530f1e5769"), "name" : [ "大姐", "二姐", "三姐", "四姐" ], "address" : "山东济南", "pv" : 2000 }
db.author_test.aggregate([{"$group":{"_id":"$address","count":{"$sum":1}}}])
查询数据 数组内的数据
db.author_test.aggregate({"$project":{"_id":1,"author":1}},{"$unwind":"$author"},{"$match":{"author":'123'}})
查询语句性能测试 参考
db.commits.find({"xxx":"xx"}).explain("executionStats")
mongodb 数组修改器 参考
mongodb数组修改器—$push、$ne、$addtoset、$pop、$pull
dt = 'xxx'
agg = md.article.aggregate([{"$project":{"_id":dt,"title":1,}},{"$limit":3}])
list(agg)