views":1}})注意,当使用修饰符时,"_id"不会改变,但是"$set"修饰符会使用>db.user.update({"_id":ObjectId(...)},{"$set":{"favoritebook":"WarandPeace"}})那么更新后的文档有一个"favoritebook"键,如果要继续修改:>db.user.update({"_id":ObjectId(...)},{"$set":{"favoritebook":"GreenEggsandHam"}})也可以使用"$unset"更改为数组类型此键被完全删除:>db.user.update({"name":joe},{"$unset":{"favoritebook":1}})"$push"修饰符如果数组存在使用,"$push"会添加一个元素到现有数组的末尾,如果数组没有改变,则创建一个新数组{"_id":ObjectId("..."),"title":"Ablogpost","content":"..."}>db.blogs.posts.update({"title":"Ablogpost"},{"$push":{"comments":{"name":"joe","email":"joe@example.com","content":"nicepost."}}})>db.blog.posts.findOne(){"_id":ObjectId("..."),"title":"博客post","content":"...","comments":[{"name":"joe","email":"joe@example.com","content":"nicepost"}]}请注意,“$push”将创建一个数组类型,可用于动态添加数据。使用"$push"一次添加多个数据,并使用"$each">db.stock.ticker.update({"_id":"GOOG"},{"$push":此时使用"$setOnInsert">db.users.update({},{"$setOnInsert":{"createdAt"newDate()}},true)更新多个文档的具体操作值通过:>Db。runCommand({getLastError:1})returnresult{"err":null,"updatedExisting":true,"n":5,"ok":true}Findentry操作查询这个collection>db.c下的所有文档。find()查询特定值的文档,可以同时添加多个条件>db.users.find({"age":20})>db.users.find({"age":20,"name":"lgy"})//指定要返回的key>db.users.find({},{"username":1,"email":1})//返回结果{"_id":ObjectId("..."),"username":"lgy","email":"lgy@example.com"}通过查询,默认返回键值"_id"。如果不想出现其他键值,使用如下:>db.users.find({},{"username":1,"_id":0})//returnresult{"username":"lgy"}查询条件查询条件:"$lt","$lte","$gt","$gte"都是比较运算符,对应<,<=,>,>=//查询18岁的用户~30:>db.users.find({"age":{"$gte":18,"$lte":30}})"$ne"表示不等于某个特定值//查询用户名是的所有用户not"lgy">db.users.find({"username":{"$ne":"lgy"}})OR查询:"$in"和"$or"两种方式执行OR查询>db.raffle.find({"ticket_no":{"$in"":[725,542,390]}})"$nin"与"$in"相反>db.raffle.find({"$or""$mod"传入两个参数,第一个作为除数,第二个用来判断余数是否是这个数>db.user.find({"id_num":{"$not":{"$mod":[5,1]}}})特定类型的查询nullnull不仅会匹配key值为null的文档,还会匹配不包含该key的文档>db.c.find({"z":null})如果只想匹配key值为null的文档,可以加上"$exists"条件:>db.c.find({"z":{"$in":[null],"$exists":true}})正则表达式>db.users.find({"name":/joey?/i})查询数组$all,可用于匹配多个元素数组//以便查找可以匹配到同时存在的两个元素的文档>db.food.find({"fruit":{"$all":["people","banana"]}})$size用于查询特定长度的数组>db.food.find({"furit":{"$size":3}})$slice用于返回匹配数组元素的子集//返回前十条评论,如果10换成-10会返回最后十个评论>db.blog.posts.findOne(criteria,{"comments":{"$slice":10}})//这个操作会跳过前23个元素并返回第24~33个元素>db.blog.posts.findOne(criteria,{"comments":{"$slice":[23,10]}})返回一个匹配的数组元素>db.blog.find({"comments.name":"bob"},{"comments.$":1})//返回结果{"id": ObjectId("..."),"comments":[{"name":"bob","email":"bob@example.com","content":"goodpost"}]}//这只会返回第一个评论查询嵌入文档现在有这样的数据{"name":{“菲rst":"joe","last":"Schmoe"},"age":45}嵌入文档查询//用点号表示“进入嵌入文档内部”的意思>db.people.find({"name.first":"joe","name.last":"Schmoe"})要正确指定一组条件而不必指定每个键,您需要使用"$elematch">db.blog。find({"comments":{$elematch":{"author":"joe","score":{"$gte":5}}}})游标查询的具体操作:>for(i=0;i<100;i++){db.collection.insert({x:i});}>varcursor=db.collection.find();>while(cursor.hasNext()){obj=cursor.next();//输出视图}###limit,skip,andsort>db.c.find().limit(3)>db.c.find().skip(3)
