mongodb常用shell
Table of Contents
查看集合信息:
- db.getCollectionInfos();
- db.collection.stats();
- db.getCollectionNames();
- db.getCollectionNames().filter(f
> f.indexOf('abc')!=
-1).forEach(doc => printjson(doc));
- db.collection.getIndexes();
db.getCollection('users').stats(); db.getCollection('users').getIndexes(); # 删除索引 db.myCollection.dropIndex("indexName");
CRUD
db.myCollection.insertOne({name: "John", age: 30}); db.myCollection.insertMany([ {name: "Alice", age: 25}, {name: "Bob", age: 35} ]); db.myCollection.findOne({age: 30}); db.myCollection.find({age: {$gt: 25}}); db.myCollection.find({age: {$gt: 25}}).forEach(function(doc) { printjson(doc); }); # 也可以写成: db.myCollection.find({age: {$gt: 25}}).forEach(doc => printjson(doc)); db.myCollection.updateOne({age: 30}, {$set: {name: "David"}}); db.myCollection.updateMany({age: {$gt: 25}}, {$inc: {age: 5}}); db.myCollection.deleteOne({age: 30}); db.myCollection.deleteMany({age: {$gt: 35}}); # 删除一个指定的集合 db.myCollection.drop();
索引
# 1. 这里的 fieldName 是要创建索引的字段名,1 表示升序排序,如果是降序可以使用 -1。 db.collection.createIndex({fieldName: 1}); # 2. 为多个字段创建复合索引: db.collection.createIndex({field1: 1, field2: -1}); # 3. 创建唯一索引: db.collection.createIndex({fieldName: 1}, {unique: true});
查询数组字段包含一个值
$elemMatch
- db.collection.find({arrayField: {$elemMatch: {$eq: 2}}});
$in
- db.collection.find({arrayField: {$in: [2]}});
集合重命名
- db.oldCollection.renameCollection("newCollection");
- db.user_scholarship_distribution.renameCollection("user_scholarship_distribution_1108");
- db.user_scholarship_distribution_copy.renameCollection("user_scholarship_distribution");