MongoDB隨機查詢返回一條或N條記錄的方法

chenfeng發表於2019-07-03

用$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" }

返回15條:

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

{ "_id" : ObjectId("5d1c5b4039ab0f9fbcd88eca"), "id" : 49283, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5b6539ab0f9fbcd904f3"), "id" : 79532, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5b8a39ab0f9fbcd979b3"), "id" : 109420, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5c8239ab0f9fbcdc5229"), "id" : 295906, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c6d9adf7032c6c7939435"), "id" : 4461, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c6bf3eb9134288dc9f3ef"), "id" : 79051, "name" : "dsf" }

{ "_id" : ObjectId("5d1c6bc0eb9134288dc98769"), "id" : 51269, "name" : "dsf" }

{ "_id" : ObjectId("5d1c72c4ee9b8d3cbbc1698d"), "id" : 24003, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c6de8df7032c6c794a42a"), "id" : 74082, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c6dfddf7032c6c794eecf"), "id" : 93191, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5d1839ab0f9fbcde28a5"), "id" : 416350, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5cbe39ab0f9fbcdd0dad"), "id" : 343910, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5c0639ab0f9fbcdaed91"), "id" : 204618, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5bd639ab0f9fbcda637d"), "id" : 169270, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5c9639ab0f9fbcdc8fb7"), "id" : 311664, "name" : "chenfeng" }


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/15498/viewspace-2649455/,如需轉載,請註明出處,否則將追究法律責任。

相關文章