测试数据:
# 测试数据
var persons = [{
name:"jim",
age:25,
email:"75431457@qq.com",
c:89,m:96,e:87,
country:"USA",
books:["JS","C++","EXTJS","MONGODB"]
},
{
name:"tom",
age:25,
email:"214557457@qq.com",
c:75,m:66,e:97,
country:"USA",
books:["PHP","JAVA","EXTJS","C++"]
},
{
name:"lili",
age:26,
email:"344521457@qq.com",
c:75,m:63,e:97,
country:"USA",
books:["JS","JAVA","C#","MONGODB"]
},
{
name:"zhangsan",
age:27,
email:"2145567457@qq.com",
c:89,m:86,e:67,
country:"China",
books:["JS","JAVA","EXTJS","MONGODB"]
},
{
name:"lisi",
age:26,
email:"274521457@qq.com",
c:53,m:96,e:83,
country:"China",
books:["JS","C#","PHP","MONGODB"]
},
{
name:"wangwu",
age:27,
email:"65621457@qq.com",
c:45,m:65,e:99,
country:"China",
books:["JS","JAVA","C++","MONGODB"]
},
{
name:"zhaoliu",
age:27,
email:"214521457@qq.com",
c:99,m:96,e:97,
country:"China",
books:["JS","JAVA","EXTJS","PHP"]
},
{
name:"piaoyingjun",
age:26,
email:"piaoyingjun@uspcat.com",
c:39,m:54,e:53,
country:"Korea",
books:["JS","C#","EXTJS","MONGODB"]
},
{
name:"lizhenxian",
age:27,
email:"lizhenxian@uspcat.com",
c:35,m:56,e:47,
country:"Korea",
books:["JS","JAVA","EXTJS","MONGODB"]
},
{
name:"lixiaoli",
age:21,
email:"lixiaoli@uspcat.com",
c:36,m:86,e:32,
country:"Korea",
books:["JS","JAVA","PHP","MONGODB"]
},
{
name:"zhangsuying",
age:22,
email:"zhangsuying@uspcat.com",
c:45,m:63,e:77,
country:"Korea",
books:["JS","JAVA","C#","MONGODB"]
}]
for(var i = 0;i<persons.length;i++){
db.persons.insert(persons[i])
}
var persons = db.persons.find({name:"jim"})
while(persons.hasNext()){
obj = persons.next();
print(obj.books.length)
}
插入一条数据
db.test.insert({x:1})
插入多条数据
for(i=5;i<10;i++)db.test.insert({x:i})
格式化显示数据
db.test.find().pretty()
查询单条数据
db.test.findOne({x:5})
查询多条数据的一共有多少条
db.test.find({x:{$lt:8}}).count()
修改数据
db.test.update({x:5},{y:99})
修改后数据变为
{ “_id” : ObjectId(“5e7d6dc6de1db55b9aa3e4f6”), “y” : 99 }
部分修改数据
db.test.update({x:100},{$set:{y:101}})
如果x:101数据不存在,就插入x:222这条数据,第三个参数为true
db.test.update({x:101},{x:222},true)
修改多条数据
db.test.update({x:50},{$set:{y:50}},{multi:true})
查询年龄大于25的name,age
db.persons.find({age:{KaTeX parse error: Expected 'EOF', got '}' at position 6: gt:25}̲},{_id:0,name:1…gt:25,KaTeX parse error: Expected 'EOF', got '}' at position 6: lt:27}̲},{_id:0,name:1…ne:“USA”}},{_id:0,name:1,country:1})
查询国籍是中国或者美国的学生信息
db.persons.find({country:{KaTeX parse error: Expected 'EOF', got '}' at position 19: …["China","USA"]}̲},{_id:0,name:1…or:[{c:{KaTeX parse error: Expected 'EOF', got '}' at position 7: gte:85}̲},{e:{gte:90}}]},{_id:0,name:1,country:1,c:1,e:1})
查询出名字中存在"li"的学生信息
db.persons.find({name:/li/i},{_id:0,name:1})
查询喜欢看MONGODB和PHP的学生
db.persons.find({books:{KaTeX parse error: Expected 'EOF', got '}' at position 22: …MONGODB","PHP"]}̲},{_id:0,name:1…size:4}},{_id:0,name:1,books:1})