我们专注攀枝花网站设计 攀枝花网站制作 攀枝花网站建设
成都网站建设公司服务热线:400-028-6601

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

MongoDB随机查询返回一条或N条记录的方法-创新互联

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

10年积累的成都网站设计、网站制作经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先做网站设计后付款的网站建设流程,更有金塔免费网站建设让你可以放心的选择与我们合作。

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条记录的方法-创新互联
当前地址:http://shouzuofang.com/article/dgohsj.html

其他资讯