码迷,mamicode.com
首页 > 数据库 > 详细

mongodb 通过嵌入文档中的字段排序

时间:2019-10-11 18:36:28      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:obj   字段   顺序   结果   tle   find   lis   EDA   sql   

 

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

  

 

mongodb 通过嵌入文档中的字段排序

标签:obj   字段   顺序   结果   tle   find   lis   EDA   sql   

原文地址:https://www.cnblogs.com/yangyuping/p/11655752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!