MongoDB学习笔记-- 插入、查找(三)

  • 建立一个集合并向该集合中添加文档

        当咱们向某集合中插入文档时,若是该集合不存在,mongodb会自动建立该集合,不需手动建立集合,同时也不须要指定文档的结构。

  • 建立并插入文档

j = {name:"mongo"}
k = {x:3}
l = {name:"wangwu"}
db.testData.insert(j)
db.testData.insert(k)
db.testData.insert(l)

  • 确认该集合是否存在

show collections

  • 查找

db.testData.find()
{ "_id" : ObjectId("4c2209f9f3924d31102bd84a"), "name" : "mongo" }
{ "_id" : ObjectId("4c2209fef3924d31102bd84b"), "x" : 3 }
All MongoDB documents must have an _id field with a unique value. These operations do not explicitly specify a value for the _id field, so mongo creates a unique ObjectId value for the field before inserting it into the collection.

  • 循环插入多个文档

for (var i = 1; i <= 25; i++) db.testData.insert( { x : i } )

{ "_id" : ObjectId("51a7dc7b2cacf40b79990be6"), "x" : 1 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be7"), "x" : 2 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be8"), "x" : 3 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be9"), "x" : 4 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bea"), "x" : 5 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990beb"), "x" : 6 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bec"), "x" : 7 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bed"), "x" : 8 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bee"), "x" : 9 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bef"), "x" : 10 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf0"), "x" : 11 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf1"), "x" : 12 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf2"), "x" : 13 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf3"), "x" : 14 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf4"), "x" : 15 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf5"), "x" : 16 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf6"), "x" : 17 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf7"), "x" : 18 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf8"), "x" : 19 }
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf9"), "x" : 20 }
  1. mongodb find() 默认只显示20条记录
  2. find() 返回一个游标,迭代标并返回更多的文档使用it操做在mongo shell。

  • 经过Mongo Shell Function插入

function insertData(dbName, colName, num) {

  var col = db.getSiblingDB(dbName).getCollection(colName);
  for (i = 0; i < num; i++) {
    col.insert({x:i});
  }
  print(col.count());
}
insertData("mydb", "testData", 200)
db.testData.count()
 


        
相关文章
相关标签/搜索