日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

MongoDB查询用法大全

發布時間:2025/3/15 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MongoDB查询用法大全 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

轉載 http://blog.163.com/lgh_2002/blog/static/440175262012052116455/

詳見官方的手冊:

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ConditionalOperators%3A%3C%2C%3C%3D%2C%3E%2C%3E%3D
版本一:
1 ) . 大于,小于,大于或等于,小于或等于
$gt:大于
$lt:小于
$gte:大于或等于
$lte:小于或等于

db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value
db.collection.find({ "field" : { $lt: value } } ); // less than : field < value
db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value
db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value

如查詢j大于3,小于4:

db.things.find({j : {$lt: 3}});
db.things.find({j : {$gte: 4}});

也可以合并在一條語句內:

db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value

2) 不等于 $ne

例子:

db.things.find( { x : { $ne : 3 } } );

3) in 和 not in ($in $nin)

db.collection.find( { "field" : { $in : array } } );

例子:

db.things.find({j:{$in: [2,4,6]}}); db.things.find({j:{$nin: [2,4,6]}});


4) 取模運算$mod

db.things.find( "this.a % 10 == 1")

可用$mod代替:

db.things.find( { a : { $mod : [ 10 , 1 ] } } )


5)? $all
$all和$in類似,但是他需要匹配條件內所有的值:
如有一個對象:

{ a: [ 1, 2, 3 ] }

下面這個條件是可以匹配的:

db.things.find( { a: { $all: [ 2, 3 ] } } );

但是下面這個條件就不行了:

db.things.find( { a: { $all: [ 2, 3, 4 ] } } );


6)? $size
$size是匹配數組內的元素數量的,如有一個對象:{ a:["foo"] },他只有一個元素:

db.things.find( { a : { $size: 1 } } );

官網上說不能用來匹配一個范圍內的元素,如果想找$size<5之類的,他們建議創建一個字段來保存元素的數量。

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements.

7)$exists

$exists用來判斷一個元素是否存在:

如:

db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回

8)? $type

$type 基于 bson type來匹配一個元素的類型,像是按照類型ID來匹配,不過我沒找到bson類型和id對照表。

db.things.find( { a : { $type : 2 } } ); // matches if a is a string
db.things.find( { a : { $type : 16 } } ); // matches if a is an int

9)正則表達式

db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是區分大小寫

10)? 查詢數據內的值

db.things.find( { colors : "red" } );

11) $elemMatch

> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )?
{ "_id" : ObjectId("4b5783300334000000000aa9"),
"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
} $elemMatch : { a : 1, b : { $gt : 1 } } 所有的條件都要匹配上才行。

注意,上面的語句和下面是不一樣的。

> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )

$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }

db.postings.find( { "author.name" : "joe" } );

注意用法是 author.name ,用一個點就行了。更詳細的可以看這個鏈接: dot notation

舉個例子:

> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})

如果我們要查詢 authors name 是Jane的, 我們可以這樣:

> db.blog.findOne({"author.name" : "Jane"})

如果不用點,那就需要用下面這句才能匹配:

db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})

下面這句:

db.blog.findOne({"author" : {"name" : "Jane"}})

是不能匹配的,因為mongodb對于子對象,他是精確匹配。

13) 元操作符 $not 取反

如:

db.customers.find( { name : { $not : /acme.*corp/i } } ); db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );

mongodb還有很多函數可以用, 如排序,統計等,請參考原文。
mongodb目前沒有或(or)操作符,只能用變通的辦法代替,可以參考下面的鏈接:
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
版本二:

shell 環境下 的操作:

? ? 1. ? 超級用戶相關:

??????? ? 1. # 進入數據庫 admin

???????????? use admin

???????? 2. # 增加或修改用戶密碼

????????? db.addUser('name','pwd')

???????? 3. # 查看用戶列表

?????? ?? ? db.system.users.find()

???????? 4. # 用戶認證

????????? db.auth('name','pwd')

???????? 5. # 刪除用戶

??????? ? ? db.removeUser('name')

? ???? ?? ? 6. # 查看所有用戶

?????? ??? show users

??????? ? 7. # 查看所有數據庫

??????? ? ? show dbs

????? ?? ? 8. # 查看所有的 collection

??? ?? ?? ? show collections

?????? ? ? 9. # 查看各 collection 的狀態

??????? ? ? db.printCollectionStats()

??????? 10. # 查看主從復制狀態

??????? ? ? db.printReplicationInfo()

??????? 11. # 修復數據庫

?????? ?? ? db.repairDatabase()

??????? 12. # 設置記錄 profiling , 0=off 1=slow 2=all

?????? ?? ? db.setProfilingLevel(1)

??????? 13. # 查看 profiling

??????? ?? show profile

????? ? ? 14. # 拷貝數據庫

?????? ??? db.copyDatabase('mail_addr','mail_addr_tmp')

??? ???? 15. # 刪除 collection

??????? ? ? db.mail_addr.drop()

??????? 16. # 刪除當前的數據庫

?????? ?? ? db.dropDatabase()

?? 2 . 增刪改

???????? 1. # 存儲嵌套的對象

???????????? db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})

???????? 2. # 存儲數組對象

???????????? db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})

???????? 3. # 根據 query 條件修改,如果不存在則插入,允許修改多條記錄

?????? ??? ? ? db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)

???????? 4. # 刪除 yy=5 的記錄

???????? ?? ? db.foo.remove({'yy':5})

???????? 5. # 刪除所有的記錄

?????? ???? ? db.foo.remove()

?? 3. 索引

??????? ? 1. # 增加索引: 1(ascending),-1(descending)

???????? 2. db.foo.ensureIndex({firstname: 1, lastname: 1}, {unique: true});

???????? 3. # 索引子對象

???????? 4. db.user_addr.ensureIndex({'Al.Em': 1})

???????? 5. # 查看索引信息

???????? 6. db.foo.getIndexes()

???????? 7. db.foo.getIndexKeys()

???????? 8. # 根據索引名刪除索引

???????? 9. db.user_addr.dropIndex('Al.Em_1')

? ? 4. 查詢

?????? ?? 1. # 查找所有

?????? ? 2. db.foo.find()

??????? 3. # 查找一條記錄

?????? ? 4. db.foo.findOne()

?????? ? 5. # 根據條件檢索 10 條記錄

?????? ? 6. db.foo.find({'msg':'Hello 1'}).limit(10)

?????? ? 7. #sort 排序

??????? 8. db.deliver_status.find({'From':'ixigua@sina.com'}).sort({'Dt',-1})

???????? 9. db.deliver_status.find().sort({'Ct':-1}).limit(1)

??????? 10. #count 操作

??????? 11. db.user_addr.count()

??????? 12. #distinct 操作 , 查詢指定列,去重復

??????? 13. db.foo.distinct('msg')

??????? 14. #”>=” 操作

??????? 15. db.foo.find({"timestamp": {"$gte" : 2}})

??????? 16. # 子對象的查找

??????? 17. db.foo.find({'address.city':'beijing'})

?? 5. 管理

?????? ?? 1. # 查看 collection 數據的大小

???????? 2. db.deliver_status.dataSize()

???????? 3. # 查看 colleciont 狀態

???????? 4. db.deliver_status.stats()

???????? 5. # 查詢所有索引的大小

???????? 6. db.deliver_status.totalIndexSize()

6. ? 高級查詢

條件操作符
$gt : >?
$lt : <?
$gte: >=?
$lte: <=?
$ne : != 、 <>?
$in : in?
$nin: not in?
$all: all?
$not: 反匹配 (1.3.3 及以上版本 )?
查詢 name <> "bruce" and age >= 18 的數據
db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});?
查詢 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的數據
db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});?
查詢 age in (20,22,24,26) 的數據
db.users.find({age: {$in: [20,22,24,26]}});?
查詢 age 取模 10 等于 0 的數據
db.users.find('this.age % 10 == 0');?
或者
db.users.find({age : {$mod : [10, 0]}});?
匹配所有
db.users.find({favorite_number : {$all : [6, 8]}});?
可以查詢出 {name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }?
可以不查詢出 {name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }?
查詢不匹配 name=B* 帶頭的記錄
db.users.find({name: {$not: /^B.*/}});?
查詢 age 取模 10 不等于 0 的數據
db.users.find({age : {$not: {$mod : [10, 0]}}});?
# 返回部分字段
選擇返回 age 和 _id 字段 (_id 字段總是會被返回 )?
db.users.find({}, {age:1});?
db.users.find({}, {age:3});?
db.users.find({}, {age:true});?
db.users.find({ name : "bruce" }, {age:1});?
0 為 false, 非 0 為 true?
選擇返回 age 、 address 和 _id 字段
db.users.find({ name : "bruce" }, {age:1, address:1});?
排除返回 age 、 address 和 _id 字段
db.users.find({}, {age:0, address:false});?
db.users.find({ name : "bruce" }, {age:0, address:false});?
數組元素個數判斷
對于 {name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } 記錄
匹配 db.users.find({favorite_number: {$size: 3}});?
不匹配 db.users.find({favorite_number: {$size: 2}});?
$exists 判斷字段是否存在
查詢所有存在 name 字段的記錄
db.users.find({name: {$exists: true}});?
查詢所有不存在 phone 字段的記錄
db.users.find({phone: {$exists: false}});?
$type 判斷字段類型
查詢所有 name 字段是字符類型的
db.users.find({name: {$type: 2}});?
查詢所有 age 字段是整型的
db.users.find({age: {$type: 16}});?
對于字符字段,可以使用正則表達式
查詢以字母 b 或者 B 帶頭的所有記錄
db.users.find({name: /^b.*/i});?
$elemMatch(1.3.1 及以上版本 )?
為數組的字段中匹配其中某個元素
Javascript 查詢和 $where 查詢
查詢 age > 18 的記錄,以下查詢都一樣
db.users.find({age: {$gt: 18}});?
db.users.find({$where: "this.age > 18"});?
db.users.find("this.age > 18");?
f = function() {return this.age > 18} db.users.find(f);?
排序 sort()?
以年齡升序 asc?
db.users.find().sort({age: 1});?
以年齡降序 desc?
db.users.find().sort({age: -1});?
限制返回記錄數量 limit()?
返回 5 條記錄
db.users.find().limit(5);?
返回 3 條記錄并打印信息
db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});?
結果
my age is 18?
my age is 19?
my age is 20?
限制返回記錄的開始點 skip()?
從第 3 條記錄開始,返回 5 條記錄 (limit 3, 5)?
db.users.find().skip(3).limit(5);?
查詢記錄條數 count()?
db.users.find().count();?
db.users.find({age:18}).count();?
以下返回的不是 5 ,而是 user 表中所有的記錄數量
db.users.find().skip(10).limit(5).count();?
如果要返回限制之后的記錄數量,要使用 count(true) 或者 count( 非 0)?
db.users.find().skip(10).limit(5).count(true);?
分組 group()?
假設 test 表只有以下一條數據
{ domain: "www.mongodb.org"?
, invoked_at: {d:"2009-11-03", t:"17:14:05"}?
, response_time: 0.05?
, http_action: "GET /display/DOCS/Aggregation"?
}?
使用 group 統計 test 表 11 月份的數據 count:count(*) 、 total_time:sum(response_time) 、 avg_time:total_time/count;?
db.test.group(?
{ cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}?
, key: {http_action: true}?
, initial: {count: 0, total_time:0}?
, reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }?
, finalize: function(out){ out.avg_time = out.total_time / out.count }?
} );?
[?
{?
"http_action" : "GET /display/DOCS/Aggregation",?
"count" : 1,?
"total_time" : 0.05,?
"avg_time" : 0.05?
}?
]

MongoDB 高級聚合查詢

MongoDB 版本為: 2.0.8?

系統為: 64 位 Ubuntu 12.04

先給他家看一下我的表結構 [Oh sorry, Mongo 叫集合 ]

如你所見,我盡量的模擬現實生活中的場景。這是一個人的實體,他有基本的 manId , manName , 有朋友 [myFriends] ,有喜歡的水果 [fruits], 而且每種水果都有喜歡的權重。

很不好的是你還看見了有個 “_class” 字段? 因為我是 Java 開發者, 我還喜歡用 Spring ,因此我選用了 Spring Data Mongo 的類庫 [ 也算是框架吧,但是我不這么覺得 ] 。

現在有很多人 Spring 見的膩了也開始煩了。是的, Spring 野心很大,他幾乎想要壟斷 Java 方面的任何事情。沒辦法我從使用 Spring 后就離不開他,以至于其他框架基本上都不用學。我學了 Spring 的很多,諸如: Spring Security/Spring Integration/Spring Batch 等。。。不發明輪子的他已經提供了編程里的很多場景,我利用那些場景解決了工作中的很多問題,也使我的工作變得很高效。從而我又時間學到它更多。 Spring Data Mongo 封裝了 mongodb java driver ,提供了和 SpringJDBC/Template 一致編程風格的 MongoTemplate 。

見: http://static.springsource.org/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoTemplate.html

不說廢話了,我們直接來 MongoDB 吧。

  • Max 和Min

我和同事在測試 Mongo 時,索引還寫了不到一半,他想查詢某個字段的最大值,結果找了半天文檔也沒找到關于 max 的函數。我也很納悶這是常規函數啊怎么不提供? 后來經過翻閱資料確定 Mongo 確實不提供直接的 max 和 min 函數。但是可以通過間接的方式 [sort 和 limit] 實現這個。

要查詢最大值我們只需要把結果集按照降序排列,取第一個值就是了。

如我的例子,我想取得集合中年齡最大的人。

1 db.person. find ({}). sort ({ "age" : -1}).limit(1)

相反如果想要年齡最小的人,只需要把 sort 中改為 {“age” : 1} 就可以了。

當然我們使用了 sort ,對于小數量的文檔是沒問題的。當對于大量數據需要給 age 建立索引,否則這個操作很耗時。

  • distinct

MongoDB的destinct命令是獲取特定字段中不同值列表的最簡單工具。該命令適用于普通字段,數組字段[myFriends]和數組內嵌文檔[fruits].

如上面的圖片,我認為 fruits 和 myFriends 字段是不同的。網上很多資料和例子都沒說到這個情景,因為我們也業務是 fruits 這樣的模型,我測試了。對于 fruits.fruitId 他也是可行的。

如上面的表結構,我想統計所有的喜歡的水果。

db.person.distinct("fruits.fruitId") // 查找對象里引入對象的值,直接加.

?他成功執行了。輸出如:

[ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]

?我想統計集合中共有多少個人 [ 按名字吧 ]

db.person.distinct("manName")

?我想統計指定個數的人的共同關注的朋友。

db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})

?輸出如:

[ "234567", "345678", "456789", "987654", "ni", "wo" ]

那么我使用 Java 呢? 我只是在演示 Mongo 的命令,用 Spring Data Mongo 是怎么操作的?

Spring Schema :

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mongo="http://www.springframework.org/schema/data/mongo"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/data/mongohttp://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"><context:property-placeholder location="classpath:mongo.properties" /><!-- Default bean name is 'mongo' --><mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" /><mongo:db-factory id="mongoDbFactory"mongo-ref="mongo"dbname="mongotest" /><bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"><constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/></bean> </beans>

? max min 的測試

@Testpublic void testMaxAndMinAge() throws Exception {Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);Person result = mongoTemplate.findOne(q, Person.class);log.info(result);q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);result = mongoTemplate.findOne(q, Person.class);log.info(result);}

? distinct 的測試:

@Testpublic void testDistinct() throws Exception {List result = mongoTemplate.getCollection("person").distinct("myFriends");for (Object o : result) {log.info(o);}log.info("==================================================================");Query query = Query.query(Criteria.where("manId").is("123456"));result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());for (Object o : result) {log.info(o);}log.info("==================================================================");result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");for (Object o : result) {log.info(o);}}

?輸出的結果為:

12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ================================================================== 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ================================================================== 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr 12-22 14:13:45 [INFO] [support.GenericApplicationContext(1020)] Closing org.springframework.context.support.GenericApplicationContext@1e0a91ff: startup date [Sat Dec 22 14:13:44 CST 2012]; root of context hierarchy

?這里我要特別說明一下, 當使用了Spring Data Mongo,如上面的findOne(query, Person.class)它就會把查詢的結果集轉換成Person類的對象。Spring Data Mongo的很多API中都這樣,讓傳入了一個Bean的class對象。因為distinct的測試是輸出list<String>的,我 使用的mongo-java-driver的api。他們都很簡單,唯一的是Query這個Spring提供的對象,希望讀者注意,他幾乎封裝了所有條件 查詢,sort,limit等信息。

轉載于:https://www.cnblogs.com/daxiongblog/p/6373442.html

總結

以上是生活随笔為你收集整理的MongoDB查询用法大全的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。