python-pymongo高級查詢


原網址:https://www.cnblogs.com/t2xingzhe/p/3555268.html

轉載 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)正則表達式

mongo支持正則表達式,如:

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

10)  查詢數據內的值

下面的查詢是查詢colors內red的記錄,如果colors元素是一個數據,數據庫將遍歷這個數組的元素來查詢。

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

11) $elemMatch

如果對象有一個元素是數組,那么$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 }

12)  查詢嵌入對象的值

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叫集合]

MongoDB 高級聚合查詢

如你所見,我盡量的模擬現實生活中的場景。這是一個人的實體,他有基本的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他也是可行的。

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

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

 他成功執行了。輸出如:

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

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

1
db.person.distinct( "manName" )

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

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

 輸出如:

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

 

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

Spring Schema:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<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/beans
           http: //www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http: //www.springframework.org/schema/context
           http: //www.springframework.org/schema/context/spring-context-3.1.xsd
           http: //www.springframework.org/schema/data/mongo
           http: //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>

 maxmin的測試

1
2
3
4
5
6
7
8
9
10
@Test
     public 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的測試:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Test
     public 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);
         }
     }

 輸出的結果為:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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等信息。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM