使用insert向集合中插入一个文档:
> db.test.insert({"name":"mrbird"})
WriteResult({ "nInserted" : 1 })
> db.test.findOne()
{ "_id" : ObjectId("58a99b8168e0d7b9f6992c69"), "name" : "mrbird" }
插入的文档没有“_id”键的话,这个操作会自动为文档添加一个“_id”键。 批量插入文档则需使用insertMany函数,函数接收一个文档数组:
> db.test.insertMany([{"name":"Jane"},{"name":"KangKang"}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("58a99d6468e0d7b9f6992c6b"),
ObjectId("58a99d6468e0d7b9f6992c6c")
]
}
> db.test.find()
{ "_id" : ObjectId("58a99b8168e0d7b9f6992c69"), "name" : "mrbird" }
{ "_id" : ObjectId("58a99d6468e0d7b9f6992c6b"), "name" : "Jane" }
{ "_id" : ObjectId("58a99d6468e0d7b9f6992c6c"), "name" : "KangKang" }
要查看一个文档的大小,可以使用Object.bsonsize(doc)函数(单位为字节):
> Object.bsonsize(db.test.find({"name":"mrbird"}))
1215