mongodb中的全部数据:
db.testInfo.find({}) .sort({_id:-1}) .limit(100)
查询结果:
/* 1 createdAt:2019/10/11 下午5:12:50*/ { "_id" : ObjectId("5da04792665cd81dc0d46d3d"), "name" : "jim2", "age" : 5, "list" : [ { "title" : "a2", "price" : 1 }, { "title" : "a1", "price" : 5 } ] }, /* 2 createdAt:2019/10/11 下午5:01:55*/ { "_id" : ObjectId("5da04503665cd81dc0d46d3c"), "name" : "leo", "age" : 4, "list" : [ { "title" : "a1", "price" : 3 }, { "title" : "d2", "price" : 2 } ] }, /* 3 createdAt:2019/10/11 下午5:01:55*/ { "_id" : ObjectId("5da04503665cd81dc0d46d3b"), "name" : "jason", "age" : 3, "list" : [ { "title" : "a1", "price" : 2 }, { "title" : "c2", "price" : 1 } ] }, /* 4 createdAt:2019/10/11 下午5:01:55*/ { "_id" : ObjectId("5da04503665cd81dc0d46d3a"), "name" : "mark", "age" : 2, "list" : [ { "title" : "a1", "price" : 3 }, { "title" : "b2", "price" : 4 } ] }, /* 5 createdAt:2019/10/11 下午5:00:12*/ { "_id" : ObjectId("5da0449c665cd81dc0d46d39"), "name" : "jim", "age" : 1, "list" : [ { "title" : "a1", "price" : 1 }, { "title" : "a2", "price" : 2 } ] }
通过嵌入文档中查询指定title的数据,然后根据price排序,注意需要排序时将查询的title也一并作为排序字段,否则顺序会错乱。
db.testInfo.find({"list.title":"a1"}) .sort({ "list.title":1, "list.price":1 });
查询结果:
/* 1 createdAt:2019/10/11 下午5:00:12*/ { "_id" : ObjectId("5da0449c665cd81dc0d46d39"), "name" : "jim", "age" : 1, "list" : [ { "title" : "a1", "price" : 1 }, { "title" : "a2", "price" : 2 } ] }, /* 2 createdAt:2019/10/11 下午5:01:55*/ { "_id" : ObjectId("5da04503665cd81dc0d46d3b"), "name" : "jason", "age" : 3, "list" : [ { "title" : "a1", "price" : 2 }, { "title" : "c2", "price" : 1 } ] }, /* 3 createdAt:2019/10/11 下午5:01:55*/ { "_id" : ObjectId("5da04503665cd81dc0d46d3a"), "name" : "mark", "age" : 2, "list" : [ { "title" : "a1", "price" : 3 }, { "title" : "b2", "price" : 4 } ] }, /* 4 createdAt:2019/10/11 下午5:01:55*/ { "_id" : ObjectId("5da04503665cd81dc0d46d3c"), "name" : "leo", "age" : 4, "list" : [ { "title" : "a1", "price" : 3 }, { "title" : "d2", "price" : 2 } ] }, /* 5 createdAt:2019/10/11 下午5:12:50*/ { "_id" : ObjectId("5da04792665cd81dc0d46d3d"), "name" : "jim2", "age" : 5, "list" : [ { "title" : "a2", "price" : 1 }, { "title" : "a1", "price" : 5 } ] }
原文地址:https://www.cnblogs.com/yangyuping/p/11655752.html
时间: 2024-11-05 15:17:29