MongoDB 插入文档
MongoDB 插入文档
在本章中,我们将学习如何在MongoDB集合中插入文档。
insert()方法
要将数据插入MongoDB集合,需要使用MongoDB的insert()或save()方法。
语法
insert()命令的基本语法如下所示
>db.COLLECTION_NAME.insert(document)
例子
>db.mycol.insert({ _id: ObjectId(7df78ad8902c), title: 'MongoDB Overview', description: 'MongoDB is no sql database', by: 'tutorials point', url: 'http://www.tutorialspoint.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 })
这里mycol是我们的收藏名称,如前一章所创建的。如果数据库中不存在该集合,则MongoDB将创建此集合,然后将文档插入其中。
在插入的文档中,如果不指定_ id参数,MongoDB将为此文档分配唯一的ObjectId。
_id是集合中每个文档唯一的12字节十六进制数。12字节划分如下
_id : ObjectId ( 4字节时间戳,3字节机器id,2字节进程id,
3字节增量器)
要在单个查询中插入多个文档,可以在insert ( )命令中传递文档数组。
例子
>db.post.insert([ { title: 'MongoDB Overview', description: 'MongoDB is no sql database', by: 'tutorials point', url: 'http://www.tutorialspoint.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 }, { title: 'NoSQL Database', description: "NoSQL database doesn't have tables", by: 'tutorials point', url: 'http://www.tutorialspoint.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 20, comments: [ { user:'user1', message: 'My first comment', dateCreated: new Date(2013,11,10,2,35), like: 0 } ] } ])
要插入文档,您还可以使用db.post.save(文档)。如果未在文档中指定_id,则save()方法的工作方式与insert()方法相同。如果指定_id,则它将替换save()方法中指定的包含_id的文档的整个数据。