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 } ] }
目前好像根据经纬度范围查询时,无法同时指定嵌入文档中的字段正确排序。只能先通过经纬度范围查询出来所有数据后,再根据嵌入文档中字段进行排序。
特殊情况下是否可以考虑固定嵌入集合数量,指定下标来对应字段排序(未测试过)。
学艺不精,如有其他办法,欢迎留言一起讨论。