置的数组修改器
若是数组有多个值,而我们只想对其中的一部分进行修改,可以通过位置或者定位操作符"$"
数组下表是从0开始的,可以将下标直接作为键来选择元素。例如:
db.blog.insert({
"_id":1001,
"content":"源辰信息科技有限公司",
"comments":[{
"comment":"很好的公司",
"author":"大军",
"votes":100
},{
"comment":"学习的乐园",
"author":"小军",
"votes":1001
},
{
"comment":"快乐地成长之地",
"author":"小小军",
"votes":100
}]
})
?
如果想要增加第一个评论的投票数,可以这么做;
db.blog.update({"_id":1001},{$inc:{"comments.0.votes":1}})
?
但很多情况下,不预先查询文档就不能知道要修改的数组的小标。为了克服这个困难,MongoDB提供了定位操作符$,用来定位查询文档已经匹配的数组元素,并进行更新。
db.blog.update({"comments.author":"小军"},{$set:{"comments.$.author":"小军哥"}});
?
MongoDB默认将只更新单一的文件,更新多个你需要设置参数置'multi' 为true
db.blog.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}},{multi:true})
db.blog.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}},false,true);
--条件查询
db.mycollection.find()
db.mycollection.findOne().pretty(); --pretty()格式化输出
db.mycollection.find({"":""}) --where =
db.mycollection.find({"":{$lt:}}) --where <
db.mycollection.find({"":{$lte:}}) --where <=
db.mycollection.find({"":{$gt:}}) --where >
db.mycollection.find({"":{$gte:}}) --where >=
db.mycollection.find({"":{$ne:}}) --where !=
--in
db.mycollection.find({"":{$in:[]}})
--and
db.mycollection.find({"name":"navy","addr":"湖南衡阳"}).pretty() --where !=
--or
db.mycollection.find({$or:[{"name":"navy"},{"addr":"湖南衡阳"}]}).pretty()
--and and or
db.mycollection.find({"name":"yc",$or:[{"name":"navy"},{"addr":"湖南衡阳"}]}).pretty()
?
?
游标操作
for(i=0;i<100;i++){
db.collection.insert({x:i});
}
var cursor=db.collection.find();
var obj;
while(cursor.hasNext()){
obj=cursor.next();
display(obj);
}
?
游标还实现了
JavaScript的迭代接口,所以可以在forEach循环中使用
cursor.forEach(function(x){
print(x)
});
db.collection.find().limit(3) --返回前三个
db.collection.find().skip(3); --略过前三个
sort接受一个对象作为参数,这个对象是一组键/值对,键对应文档的键名,值为排序规则。1为升序,-1为降序。
db.collection.sort({username:1,age:-1});
?
?
分页每页10条
第一页:db.collection.find({"desc":"mp3"}).limit(10).sort({"price":-1});
下一页:db.collection.find({"desc":"mp3"}).skip(10).limit(10).sort({"price":-1});
?
索引:
db.collection.ensureIndex({"age":1,"username":1}) --在age和username上建立符合索引
?