阅读(1069) (0)

MongoDB 插入文档

2017-01-09 19:13:18 更新

MongoDB教程 - MongoDB插入文档


要将数据插入MongoDB集合,请使用MongoDB的insert()或save()方法。

语法

以下代码显示了insert()命令的语法:

>db.COLLECTION_NAME.insert(document)

例子

>db.mycol.insert({
   _id: ObjectId(2df22ad2222c),
   title: "MongoDB Tutorial", 
   description: "MongoDB is no sql database",
   by: "www.zijiebao.com",
   url: "http://www.zijiebao.com",
   tags: ["mongodb", "database", "NoSQL","tutorial","big data"],
   likes: 100
})

mycol 集合名称。如果集合不存在,MongoDB将创建此集合,然后将文档插入其中。

如果我们不指定_id参数,那么MongoDB将为此文档分配唯一的ObjectId。

>db.post.insert([
{
   title: "MongoDB Overview", 
   description: "MongoDB is no sql database",
   url: "http://www.zijiebao.com",
   tags: ["mongodb", "database", "NoSQL","tutorial","big data"],
   likes: 122
},
{
   title: "MongoDB setup", 
   description: "NoSQL database is schema less",
   url: "http://www.zijiebao.com",
   tags: ["mongodb", "database", "NoSQL","tutorial","big data"],
   likes: 22, 
   comments: [  
      {
         user:"user1",
         message: "My first comment",
         dateCreated: new Date(2014,10,10,2,35),
         like: 0 
      }
   ]
}
])

要插入文档,您还可以使用db.post.save(document)。