1. 程式人生 > >mongodb CRUD操作

mongodb CRUD操作

monogodb CRUD

# ./mongod

2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten] MongoDB starting : pid=36578 port=27017 dbpath=/data/db 64-bit host=IBG-opensource-DB-cwT13
2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten] db version v3.6.2
2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten] git version: 489d177dbd0f0420a8ca04d39fd78d0a2c539420
2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten] allocator: tcmalloc
2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten] modules: none
2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten] build environment:
2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten]     distmod: rhel70
2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten]     distarch: x86_64
2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten]     target_arch: x86_64
2018-04-15T18:52:36.352+0800 I CONTROL  [initandlisten] options: {}
2018-04-15T18:52:36.354+0800 I -        [initandlisten] Detected data files in /data/db created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
2018-04-15T18:52:36.354+0800 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=7423M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),statistics_log=(wait=0),verbose=(recovery_progress),
2018-04-15T18:52:36.512+0800 I STORAGE  [initandlisten] WiredTiger message [1523789556:512963][36578:0x7f6aac8c2b00], txn-recover: Main recovery loop: starting at 2/35072
2018-04-15T18:52:36.615+0800 I STORAGE  [initandlisten] WiredTiger message [1523789556:615462][36578:0x7f6aac8c2b00], txn-recover: Recovering log 2 through 3
2018-04-15T18:52:36.676+0800 I STORAGE  [initandlisten] WiredTiger message [1523789556:676715][36578:0x7f6aac8c2b00], txn-recover: Recovering log 3 through 3
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] 
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] 
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] ** WARNING: This server is bound to localhost.
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] **          Remote systems will be unable to connect to this server. 
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] **          Start the server with --bind_ip <address> to specify which IP 
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] **          addresses it should serve responses from, or with --bind_ip_all to
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] **          bind to all interfaces. If this behavior is desired, start the
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] **          server with --bind_ip 127.0.0.1 to disable this warning.
2018-04-15T18:52:36.740+0800 I CONTROL  [initandlisten] 
2018-04-15T18:52:36.741+0800 I CONTROL  [initandlisten] 
2018-04-15T18:52:36.741+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2018-04-15T18:52:36.741+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2018-04-15T18:52:36.741+0800 I CONTROL  [initandlisten] 
2018-04-15T18:52:36.741+0800 I CONTROL  [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 65535 processes, 655350 files. Number of processes should be at least 327675 : 0.5 times number of files.
2018-04-15T18:52:36.741+0800 I CONTROL  [initandlisten] 
2018-04-15T18:52:36.755+0800 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'
2018-04-15T18:52:36.756+0800 I NETWORK  [initandlisten] waiting for connections on port 27017



# ./mongo

MongoDB shell version v3.6.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.2
Server has startup warnings: 
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] 
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] 
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] ** WARNING: This server is bound to localhost.
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] **          Remote systems will be unable to connect to this server. 
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] **          Start the server with --bind_ip <address> to specify which IP 
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] **          addresses it should serve responses from, or with --bind_ip_all to
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] **          bind to all interfaces. If this behavior is desired, start the
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] **          server with --bind_ip 127.0.0.1 to disable this warning.
2018-04-15T11:01:19.795+0800 I CONTROL  [initandlisten] 
2018-04-15T11:01:19.796+0800 I CONTROL  [initandlisten] 
2018-04-15T11:01:19.796+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2018-04-15T11:01:19.796+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2018-04-15T11:01:19.796+0800 I CONTROL  [initandlisten] 
2018-04-15T11:01:19.796+0800 I CONTROL  [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 65535 processes, 655350 files. Number of processes should be at least 327675 : 0.5 times number of files.
2018-04-15T11:01:19.796+0800 I CONTROL  [initandlisten]



https://docs.mongodb.com/manual/reference/method/db.collection.insert/


一、插入文檔

插入行為,,如果集合不存在,則創建

Collection Creation:

If the collection does not currently exist, insert operations will create the collection.


方法:

  • insertOne

db.collection.insertOne(
   <document>,
   {
      writeConcern: <document>   //Optional. A document expressing the write concern. Omit to use the default write concern.
   }
)

註意:

集合不存在該操作會創建集合。

該操作不支持 db.collection.explain() 查詢計劃 可以使用insert 代替。


_id Field:


If the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document.


ObjectId值由12個字節組成,其中前四個字節是反映ObjectId創建的時間戳,具體為:

a 4-byte value representing the seconds since the Unix epoch,

a 3-byte machine identifier,

a 2-byte process id, and

a 3-byte counter, starting with a random value.


> db.products.insertOne( { item: "card", qty: 15 } );

{
"acknowledged" : true,         返回值
"insertedId" : ObjectId("5ad2c1572c23d0642cd35b48")
}
> db.products.find();
{ "_id" : ObjectId("5ad2c1572c23d0642cd35b48"), "item" : "card", "qty" : 15 }


> db.products.insertOne(

{ "item": "envelopes", "qty": 100, type: "Self-Sealing" },

{ writeConcern: { w : "majority", wtimeout : 100 } } //w:majority,表示>1/2的節點有數據

)

{
"acknowledged" : true,
"insertedId" : ObjectId("5ad2cecd2c23d0642cd35b4c")
}


  • insertMany

db.collection.insertMany(
   { [ <document 1> , <document 2>, ... ] },//An array of documents to insert into the collection. 註意是數組
   {
      writeConcern: <document>,
      ordered: <boolean>   //Optional. A boolean specifying whether the mongod instance should perform an ordered or unordered insert. Defaults to true.   默認式按照順序添加的    順序添加的速度要慢於不按順序添加的
   }
)



註意:

每一組操作最大可以有1000個文檔。

順序添加的速度要慢於不按順序添加的。

不存在的集合會自動創建。

insertMany() 也不支持db.collection.explain() 可以使用insert 代替。

如果添加出錯會報出 BulkWriteError exception 異常,按照順序添加的 操作遇到錯誤會直接停止,而不按照順序的會繼續執行在隊列中的寫操作。


> db.products.insertMany( [

{ item: "card", qty: 15 },

{ item: "envelope", qty: 20 },

{ item: "stamps" , qty: 30 }

] , { w: "majority", wtimeout: 100 }

);


{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5ad2c2332c23d0642cd35b49"),
ObjectId("5ad2c2332c23d0642cd35b4a"),
ObjectId("5ad2c2332c23d0642cd35b4b")
]
}


  • insert

db.collection.insert(  #同時又insertOne 和insertMany的功能
   <document or array of documents>,  //數組或者文檔都可以添加
   {
     writeConcern: <document>,
     ordered: <boolean> //跟insertMany()操作作用一致
   }
)


db.products.insert( [

{ item: "card", qty: 15 },

{ item: "envelope", qty: 20 },

{ item: "stamps" , qty: 30 }

] , { w: "majority", wtimeout: 100 }

);


db.products.insert( { item: "card", qty: 40 } );



Additional Methods for Inserts

when used with the upsert: true option:以下方法當沒有查詢條件匹配時創建新文檔,默認是false。


db.collection.update()          
db.collection.updateOne()        
db.collection.updateMany()      
db.collection.findAndModify()    
db.collection.findOneAndUpdate()
db.collection.findOneAndReplace()
db.collection.save()
db.collection.bulkWrite()


mongodb CRUD操作