MongoDB insert document

an introduction
This section will show you how to insert data into a MongoDB collection.
The data structure of the document is basically the same as JSON.
All data stored in the collection is in BSON format.
BSON is a json-like storage format in binary form, referred to as Binary JSON.
 
Second insert document
MongoDB uses the insert() or save() methods to insert documents into the collection, the syntax is as follows:
db.COLLECTION_NAME.insert(document)
 
Three examples
The following documents are stored in the col collection of MongoDB's runoob database:
  1. > use runoob
  2. switched to db runoob
  3. > db.col.insert({title: 'MongoDB 教程',
  4. ... description: 'MongoDB 是一个 Nosql 数据库',
  5. ... by: '菜鸟教程',
  6. ... url: 'http://www.runoob.com',
  7. ... tags: ['mongodb', 'database', 'NoSQL'],
  8. ... likes: 100
  9. ... })
  10. WriteResult({ "nInserted" : 1 })
In the above example, col is our collection name. If the collection is not in the database, MongoDB will automatically create the collection and insert the document.
View inserted documents:
> db.col.find()
{ "_id" : ObjectId("593b6160bcd6757fd2d302fd"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "菜鸟教程", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
>
 
We can also define the data as a variable like this:
  1. > document=({title: 'MongoDB 教程',
  2. ... description: 'MongoDB 是一个 Nosql 数据库',
  3. ... by: '菜鸟教程',
  4. ... url: 'http://www.runoob.com',
  5. ... tags: ['mongodb', 'database', 'NoSQL'],
  6. ... likes: 100
  7. ... });
The result displayed after execution is as follows:
  1. {
  2. "title" : "MongoDB 教程",
  3. "description" : "MongoDB 是一个 Nosql 数据库",
  4. "by" : "菜鸟教程",
  5. "url" : "http://www.runoob.com",
  6. "tags" : [
  7. "mongodb",
  8. "database",
  9. "NoSQL"
  10. ],
  11. "likes" : 100
  12. }
To perform an insert operation:
  1. > db.col.insert(document)
  2. WriteResult({ "nInserted" : 1 })
Four save commands
To insert a document you can also use the db.col.save(document) command.
如果不指定 _id 字段 save() 方法类似于 insert() 方法。
如果指定 _id 字段,则会更新该 _id 的数据。

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327073679&siteId=291194637