Recipe 2-1. Create a Collection(创建一个容器)
1.创建容器
db.createCollection("person")
2.查看已经创建的容器
show collections
Recipe 2-2. Create Capped Collections(创建有限制容器)
1.创建一个student容器,字节大小是1000,最大存放文档(document)是2
db.createCollection("student",{capped: true,size:1000,max:2})
2.查看是否是有限制的容器
db.student.isCaped()
3.插入数据
db.student.insert([{ "_id" : 10001, "name" : "Taanushree AS", "age" : 10 },{ "_id" : 10002, "name" : "Aruna M S", "age" :14 }])
4.查看数据,会看到插入的两条数据10001和10002
db.student.find()
5.按照降序查看数据,默认是_id
db.student.find().sort({$natural:-1})
6.由于容器中已经有2条数据,是到达瓶颈了,所以再次插入数据,之前的其中一条数据会被覆盖
db.student.insert({_id:10003,name:"Anba V M",age:16})WriteResult({ "nInserted" : 1 })
7.再次查看数据,发现10001数据被10003替换了
Recipe 2-3. Insert Documents(插入文档,即数据)
插入的命令有这三个
db.collection.insertOne inserts a single document
db.collection.insertMany inserts multiple documents
db.collection.insert inserts a single document or multiple documents
1.插入一条数据
db.person.insertOne({_id:1001,name:"Taanushree AS",age:10})
2.插入多条数据
db.person.insertMany([{_id:1003,name:"Anba V M",age:16},{_id:1004,name:"shobana",age:44}])
Recipe 2-4. Query Documents(查询文档,即数据)
1.查询所有数据
db.person.find({}) 或 db.person.find()
2.指定条件查询
db.person.find({name:"shobana"})
3.使用查询符号,如以下例子,age大于10的数据
db.person.find({age:{$gt:10}})
4.查询并的关系,如下例子,name和age两条件都要满足
db.person.find({ name:"shobana",age:{$gt:10}})
5.查询或的关系,如下例子,name或age其中之一满足即可
db.person.find( { $or: [ { name: "shobana" }, { age: { $eq:20 } } ] } )
Recipe 2-5. Update Documents(更新文档,即数据)
更新的命令有:
db.collection.updateone to modify a single document
db.collection.updateMany to modify multiple documents
db.collection.replaceone to replace the first matching document in the collection that matches the filter
1.更新一条数据
db.student.updateOne({name: "Joshi"},{$set:{"marks.english": 20}})
2.更新多条数据
db.student.updateMany( { "result":"fail" }, { $set: { "marks.english": 20, marks.maths: 20 } })
3.替换一个文档,即整条数据
db.student.replaceOne( { name: "John" }, {_id:1001,name:"John",marks:{english:36,maths:39},result:"pass"})
4.注意,以上更新不能更新_id
Recipe 2-6. Delete Documents(删除文档,即数据)
删除的命令有:
db.collection.deleteOne to delete a single document
db.collection.updateMany to delete multiple documents
1.只删除一条记录
db.student.deleteOne({name: "John"})
2.删除多条记录
db.student.deleteMany({name: "Jack"})
3.删除容器中所有的文档(数据)
db.student.deleteMany({})
Recipe 2-7. Work with Mongo Import(导入数据)
1.在 C:\Sample\文件夹下创建一个student.csv文件。内容如下:
_id,name,class
1,John,II
2,James,III
3,Joshi,I
2.执行以下语句(控制台切换到Mongodb安装的bin目录就行,不需要进入mongodb)
mongoimport --db student --collection students --type csv --headerline --file c:\Sample\student.csv
3.查询数据
use student
show collections
db.students.find()
Recipe 2-8. Work with Mongo Export(导出数据)
1.执行如下命令
C:\Program Files\MongoDB\Server\4.0\bin>mongoexport --db student --collection students --out C:\Sample\student.json
Recipe 2-9. Query Embedded Documents(查询嵌套文档,即数据)
1.employee的address又是一个文档,所以查询是
db.employee.find( { address: { previous:"Cresent Street",current:"234,Bald Hill Street" }} )
2.查询嵌套文档的某个域,如address中的previous作为条件
db.employee.find( { "address.previous": "Cresent Street" } )
Recipe 2-10. Working with Arrays(数组使用)
准备数据
db.employeedetails.insertMany([
{ name: "John", projects: ["MongoDB", "Hadoop","Spark"],scores:[25,28,29] },
{ name: "James", projects: ["Cassandra","Spark"], scores:[26,24,23]},
{ name: "Smith",projects: [ "Hadoop","MongoDB"], scores:[22,28,26]} ] )
1.匹配一个数组
db.employeedetails.find( { projects: ["Hadoop", "MongoDB"] } )
2.查询数据中指定有某个元素
db.employeedetails.find( { projects: "MongoDB" } )
3.使用操作符号查询,如scores中大于26的数据
db.employeedetails.find( { scores:{$gt:26} } )
4.使用操作符查询数据中的范围,如scores中大于20小于24
db.employeedetails.find( { scores: { $gt: 20, $lt: 24 } } )
5.使用$elemMatch操作符--可以指定多个条件
db.employeedetails.find( { scores: { $elemMatch: { $gt: 23,$lt: 27 } } } )
6.通过索引查询一个数组元素,如scores的第二个元素大于26的数据
db.employeedetails.find( { "scores.2": { $gt: 26 } } )
7.使用$size操作,查询数组的数量,如下是数据元素数量是2的
db.employeedetails.find( { "projects": { $size: 2 } } )
8.使用$push操作
添加新的数组到指定的数据上
db.employeedetails.update({name: "Smith"},{$push:{Location:{$each:["US","UK"]}}})
9.使用$addToSet操作
添加一个新的数组到指定的数据上
db.employeedetails.update( {name: "James"}, { $addToSet:{hobbies: [ "drawing", "dancing"]} })
10.使用$pop来移除数组中的第一条或最后一条数据
移除数组中的第一条数据
db.employeedetails.update( {name: "James"},{ $pop:{scores:-1}})
移除数组中最后一条数据
db.employeedetails.update( {name: "James"},{ $pop: {scores:1}})
Recipe 2-11. Query an Array of Embedded Documents(查询嵌套数组)
1.数据准备
use student
db.studentmarks.insertMany([{name:"John",marks:[{class: "II", total: 489},{ class: "III", total: 490 }]},
{name:"James",marks:[{class: "III", total: 469 },{class: "IV",total: 450}]},
{name:"Jack",marks:[{class:"II", total: 489 },{class: "III", total: 390}]},
{name:"Smith", marks:[{class:"III", total: 489}, {class: "IV", total: 490}]},
{name:"Joshi",marks:[{class: "II", total: 465}, { class: "III",total: 470}]}])
2.查询marks的class为II和total为489
db.studentmarks.find( { "marks": {class: "II", total: 489}})
3.数组的一个域用于条件
db.studentmarks.find( { 'marks.total': { $lt: 400 } } )
4.数组的索引域用于查询条件
db.studentmarks.find( { 'marks.0.class': "II" } )
Recipe 2-12. Restricting the Fields Returned from a Query(从查询中约束域的返回)
准备数据
db.studentdetails.insertMany( [
{name: "John", result: "pass",marks: { english: 25, maths: 23, science: 25 }, grade: [ {class: "A", total: 73 } ] },
{name: "James", result: "pass",marks: { english: 24, maths: 25, science: 25 }, grade: [ {class: "A", total: 74 } ] },
{name: "James", result: "fail",marks: { english: 12, maths: 13, science: 15 }, grade: [ {class: "C", total: 40 } ] }])
1.查询返回指定的域,如下查询只要_id,marks和result
db.studentdetails.find( { name: "John" }, { marks: 1, result: 1} )
2.查询指定返回的域,但不需要_id
db.studentdetails.find( { name: "John" }, { marks: 1, result:1,_id:0 } )
3.查询排队某些域不需要显示,如下,result和_id不需要返回
db.studentdetails.find( { name: "John" }, { result:0,_id:0 } )
4.在嵌套文档中,指定返回某个域,如下只要嵌套的marks的english就行
db.studentdetails.find( { name: "John }, { result:1, grade: 1,"marks.english": 1 })
Recipe 2-13. To Query Null or Missing Fields(查询空或没有的域)
1.插入数据
db.sample.insertMany([{ _id: 1, name: null }, { _id: 2 }]){ "acknowledged" : true, "insertedIds" : [ 1, 2 ] }
2.查询name为null
db.sample.find( { name: null } )
3.使用$type指定null,即$type的10代表null
db.sample.find( { name: { $type: 10 } } )
4.使用$exists来过滤出null
db.sample.find( { name: { $exists: false } } )
Recipe 2-14. Iterate a Cursor(遍历)
1.插入数据
db.numbers.insert({_id:1,number:1});
db.numbers.insert({_id:2,number:2});
db.numbers.insert({_id:3,number:3});
db.numbers.insert({_id:4,number:4});
db.numbers.insert({_id:5,number:5});
db.numbers.insert({_id:6,number:6});
db.numbers.insert({_id:7,number:7});
db.numbers.insert({_id:8,number:8});
db.numbers.insert({_id:9,number:9});
db.numbers.insert({_id:10,number:10});
db.numbers.insert({_id:11,number:11});
db.numbers.insert({_id:12,number:12});
db.numbers.insert({_id:13,number:13});
db.numbers.insert({_id:14,number:14});
db.numbers.insert({_id:15,number:15});
db.numbers.insert({_id:16,number:16});
db.numbers.insert({_id:17,number:17});
db.numbers.insert({_id:18,number:18});
db.numbers.insert({_id:19,number:19});
db.numbers.insert({_id:20,number:20});
db.numbers.insert({_id:21,number:21});
db.numbers.insert({_id:22,number:22});
db.numbers.insert({_id:23,number:23});
db.numbers.insert({_id:24,number:24});
db.numbers.insert({_id:25,number:25});
2.使用发下操作查询
> var myCursor = db.numbers.find()
> myCursor
3.还可以用这个操作查询
var myCursor=db.numbers.find({});
while(myCursor.hasNext()){
print(tojson(myCursor.next()));
}
4.还可以用这个操作查询
> var myCursor = db.numbers.find()
> myCursor.forEach(printjson);
Recipe 2-15. limit() and skip() Methods(limit和skip方法)
1.查询两条数据
db.numbers.find().limit(2)
2.跳过前5条数据
db.numbers.find().skip(5)