当前位置:数据库 > mongodb >>

MongoDB学习笔记-- 插入、查找

MongoDB学习笔记-- 插入、查找
 
创建一个集合并向该集合中添加文档
        当我们向某集合中插入文档时,如果该集合不存在,mongodb会自动创建该集合,不需手动创建集合,同时也不需要指定文档的结构。
创建并插入文档
1
j = {name:"mongo"}
2
k = {x:3}
3
l <span></span>= {name:"wangwu"}
1
db.testData.insert(j)
2
db.testData.insert(k)
3
db.testData.insert(l)

 

确认该集合是否存在
 
1
show collections

 

 
 
 
查找
1
db.testData.find()
1
{ "_id" : ObjectId("4c2209f9f3924d31102bd84a"), "name" : "mongo" }
2
{ "_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.
循环插入多个文档
1
for (var i = 1; i <= 25; i++) db.testData.insert( { x : i } )

01
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be6"), "x" : 1 }
02
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be7"), "x" : 2 }
03
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be8"), "x" : 3 }
04
{ "_id" : ObjectId("51a7dc7b2cacf40b79990be9"), "x" : 4 }
05
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bea"), "x" : 5 }
06
{ "_id" : ObjectId("51a7dc7b2cacf40b79990beb"), "x" : 6 }
07
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bec"), "x" : 7 }
08
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bed"), "x" : 8 }
09
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bee"), "x" : 9 }
10
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bef"), "x" : 10 }
11
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf0"), "x" : 11 }
12
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf1"), "x" : 12 }
13
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf2"), "x" : 13 }
14
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf3"), "x" : 14 }
15
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf4"), "x" : 15 }
16
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf5"), "x" : 16 }
17
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf6"), "x" : 17 }
18
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf7"), "x" : 18 }
19
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf8"), "x" : 19 }
20
{ "_id" : ObjectId("51a7dc7b2cacf40b79990bf9"), "x" : 20 }

 

mongodb find() 默认只显示20条记录
find() 返回一个游标,迭代游标并返回更多的文档使用it操作在mongo shell。
通过Mongo Shell Function插入
1
function insertData(dbName, colName, num) {
2

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

 

 
 
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,