MongoDB 隨機查詢 返回指定個數


用$sample (aggregation)方法,具體命令為:

db.collection.aggregate( [ { $sample: { size: N } } ] ) N為條數

例如返回5條:

> db.test.aggregate( [ { $sample: { size: 5 } } ] )

{ "_id" : ObjectId("5d1c5a7b39ab0f9fbcd647a8"), "id" : 1, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c733bee9b8d3cbbc26779"), "id" : 89007, "name" : "hello" }

{ "_id" : ObjectId("5d1c7342ee9b8d3cbbc276dc"), "id" : 92946, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c7240df7032c6c7966207"), "id" : 88223, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5b7c39ab0f9fbcd94c62"), "id" : 97819, "name" : "chenfeng" }


返回1條:

> db.test.aggregate( [ { $sample: { size: 1 } } ] )

{ "_id" : ObjectId("5d1c5aec39ab0f9fbcd7b29a"), "id" : 92915, "name" : "chenfeng" }

 

帶條件查詢:

myresult1=db.aggregate(collection,[{"$match":{"_id.start_time":{"$gte":vstart_time,"$lte":vend_time},"site_address":vsitec,"_id.imsi":{"$ne":data}}},{"$group":{"_id":{"imsi":"$_id.imsi","site_address":"$site_address"},"count":{"$sum":1}}}])


免責聲明!

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



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