mongodb 安装使用备记

# 1.1 安装
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
echo "deb [ arch=amd64 ] http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
sudo apt-get update
sudo apt-get install -y mongodb-org

# 1.2 启停
sudo service mongod start
sudo service mongod stop
sudo service mongod restart

# 1.3 卸载
sudo apt-get purge mongodb-org*
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb

# 1.4 链接
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
mongodb://localhost,localhost:27018,localhost:27019
# 2.1 数据库操作
mongo  # 进入shell
use jkTest;
db.createCollection('users');
show dbs;  # 发现已经创建myTest数据库
db.help();
db.users.help();
db.users.find().help();
db.dropDatabase();  # 删除数据库

# 2.2 用户操作
db.addUser("user_00");
db.addUser("user_00", "test123", true); 添加用户、设置密码、是否只读
db.removeUser("user_00"); #删除用户
show users;  # 查看用户情况


# 3.1 增
db.users.insertOne({userName: 'jkmiao', age: 25, sex: true}); # insertMany() , save before 3.2 version

db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
   { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
   { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])



# 3.2 删
db.users.remove({age: 20}, {justOne: 1});   # remove all 
db.books.update( { _id: 1 }, { $unset: { tags: 1 } } )  # remove some field

# 3.3 改

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,  # 找不到就新插入, 默认false
     multi: <boolean>,   # 遍历所有进行更新,默认false
     writeConcern: <document>, # 
     collation: <document>  # dict, 校对, 抛出异常的级别
   }
)

# ============================

# origin:
{
  _id: 1,
  item: "TBD",
  stock: 0,
  info: { publisher: "1111", pages: 430 },
  tags: [ "technology", "computer" ],
  ratings: [ { by: "ijk", rating: 4 }, { by: "lmn", rating: 5 } ],
  reorder: false
}
# update
db.books.update(
   { _id: 1 },
   {
     $inc: { stock: 5 },
     $set: {
       item: "ABC123",
       "info.publisher": "2222",
       tags: [ "software" ],
       "ratings.1": { by: "xyz", rating: 3 }
     }
   },
    {
    upsert: true
    }
)
# after
{
  "_id" : 1,
  "item" : "ABC123",
  "stock" : 5,
  "info" : { "publisher" : "2222", "pages" : 430 },
  "tags" : [ "software" ],
  "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
  "reorder" : false
}



# 3.4 查
db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);  # 只显示age列
db.users.find({age: {$lte: 28}}, {age: false, '_id':false}).forEach(printjson);  # 排除age列

db.collection.find( { a: 5, b: { $in: [ 1, 2, 3 ] } } ).count()
db.collection.find( { a: { $gt: 5 }, b: 5 } ).count()
db.collection.find( { a: 5, b: 5, c: 5 } )

 db.users.find({ 'age':{$lte:15}, $or: [{name:'user_11'}, {name: 'user_15'}]}).sort({age:1});


# 按条件查数量
db.collection.aggregate(
   [
      { $match: <query condition> },
      { $group: { _id: null, count: { $sum: 1 } } }
   ]
)
# 3.5 高阶使用

# 聚合查询

# origin:

{ _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 }
{ _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 }
{ _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 }
{ _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 }
{ _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }

# aggregate: group by and sum

db.orders.aggregate([
                     { $match: { status: "A" } },
                     { $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
                     { $sort: { total: -1 } }
                   ])

# after:

{ "_id" : "xyz1", "total" : 100 }
{ "_id" : "abc1", "total" : 75 }

# 查询修改删除
db.users.findAndModify({
    query: {age: {$gte: 25}}, 
    sort: {age: -1}, 
    update: {$set: {name: 'a2'}, $inc: {age: 2}},
    remove: true
});
db.runCommand({ findandmodify : "users", 
    query: {age: {$gte: 25}}, 
    sort: {age: -1}, 
    update: {$set: {name: 'a2'}, $inc: {age: 2}},
    remove: true
});


# bulkWrite
db.collection.bulkWrite(
   [
      { insertOne : <document> },
      { updateOne : <document> },
      { updateMany : <document> },
      { replaceOne : <document> },
      { deleteOne : <document> },
      { deleteMany : <document> }
   ],
   { ordered : false }
)
# 语句块
for(var i = 10; i < 30; i++){db.users.save({name: "user_" + i, age: 22 + i, sex: i % 2})};
原文地址:https://www.cnblogs.com/jkmiao/p/6936529.html