网站建设资讯

NEWS

网站建设资讯

MongoDB随机查询返回一条或N条记录的方法

用$sample (aggregation)方法,具体命令为:

创新互联是少有的网站建设、做网站、营销型企业网站、微信小程序、手机APP,开发、制作、设计、买链接、推广优化一站式服务网络公司,于2013年创立,坚持透明化,价格低,无套路经营理念。让网页惊喜每一位访客多年来深受用户好评

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


当前标题:MongoDB随机查询返回一条或N条记录的方法
网站URL:http://cdweb.net/article/gchges.html