insert
UK[?n?s?:t] US[?n?s?:rt]
vt.Insert; embed; (in the article) add; insert
n. Insertion; addition (especially a small picture inserted or overprinted in a printed page); insert (of a book or newspaper); addition
MongoDB insert() method syntax
Function: insert() method inserts a document into the collection
Syntax: db.COLLECTION_NAME.insert(document)
MongoDB insert() method example
以下文檔可以存儲在 MongoDB 的 php 數(shù)據(jù)庫 的 col集合中: >db.col.insert({title: 'MongoDB 教程', description: 'MongoDB 是一個 Nosql 數(shù)據(jù)庫', by: 'php中文網(wǎng)', url: 'http://miracleart.cn', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 }) 以上實例中 col 是我們的集合名,前一章節(jié)我們已經(jīng)創(chuàng)建過了,如果該集合不在該數(shù)據(jù)庫中, MongoDB 會自動創(chuàng)建該集合并插入文檔。 查看已插入文檔: > db.col.find() { "_id" : ObjectId("56064886ade2f21f36b03134"), "title" : "MongoDB 教程", "description" : "MongoDB 是一個 Nosql 數(shù)據(jù)庫", "by" : "php中文網(wǎng)", "url" : "http://miracleart.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } > 我們也可以將數(shù)據(jù)定義為一個變量,如下所示: > document=({title: 'MongoDB 教程', description: 'MongoDB 是一個 Nosql 數(shù)據(jù)庫', by: 'php中文網(wǎng)', url: 'http://miracleart.cn', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 }); 執(zhí)行后顯示結(jié)果如下: { "title" : "MongoDB 教程", "description" : "MongoDB 是一個 Nosql 數(shù)據(jù)庫", "by" : "php中文網(wǎng)", "url" : "http://miracleart.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } 執(zhí)行插入操作: > db.col.insert(document) WriteResult({ "nInserted" : 1 }) > 插入文檔你也可以使用 db.col.save(document) 命令。如果不指定 _id 字段 save() 方法類似于 insert() 方法。如果指定 _id 字段,則會更新該 _id 的數(shù)據(jù)。