MongoDB通过聚合查找按连接结果排序
我有两个收藏MongoDB通过聚合查找按连接结果排序,mongodb,Mongodb,我有两个收藏user和post > db.user.find().pretty() { "_id" : ObjectId("5d1473bc1b48d9309580a9de"), "user_id" : NumberLong(1), "region" : "US", "is_join" : true } { "_id" : ObjectId("5d1473bc1b48d9309580a9df"), "user_id" : NumberLong
user
和post
> db.user.find().pretty()
{
"_id" : ObjectId("5d1473bc1b48d9309580a9de"),
"user_id" : NumberLong(1),
"region" : "US",
"is_join" : true
}
{
"_id" : ObjectId("5d1473bc1b48d9309580a9df"),
"user_id" : NumberLong(2),
"region" : "KR",
"is_join" : true
}
{
"_id" : ObjectId("5d1473bc1b48d9309580a9e0"),
"user_id" : NumberLong(3),
"region" : "US",
"is_join" : true
}
{
"_id" : ObjectId("5d1473bc1b48d9309580a9e1"),
"user_id" : NumberLong(4),
"region" : "US",
"is_join" : true
}
{
"_id" : ObjectId("5d1487fc1b48d9321ff5dc1f"),
"user_id" : NumberLong(5),
"region" : "US",
"is_join" : true
}
我想通过mongo聚合查找操作加入
所以我提出了这样的问题
db.user.aggregate([
{
'$match': {
'region': 'US',
}
},
{
'$lookup': {
'from': 'post',
'localField': 'user_id',
'foreignField': 'user_id',
'as': 'user'
}
},
{
'$project': {
'_id': 0,
'user.post_id': 1
}
}
])
结果
{ "user" : [ { "post_id" : NumberLong(2) }, { "post_id" : NumberLong(5) } ] }
{ "user" : [ { "post_id" : NumberLong(1) } ] }
{ "user" : [ { "post_id" : NumberLong(4) } ] }
{ "user" : [ ] }
{ "user" : [ { "post_id" : NumberLong(1) } ] }
{ "user" : [ { "post_id" : NumberLong(2) } ] }
{ "user" : [ { "post_id" : NumberLong(4) } ] }
{ "user" : [ { "post_id" : NumberLong(5) } ] }
正如您所知,post\u id
是无序的
但我想按降序排序
期望的结果
{ "user" : [ { "post_id" : NumberLong(2) }, { "post_id" : NumberLong(5) } ] }
{ "user" : [ { "post_id" : NumberLong(1) } ] }
{ "user" : [ { "post_id" : NumberLong(4) } ] }
{ "user" : [ ] }
{ "user" : [ { "post_id" : NumberLong(1) } ] }
{ "user" : [ { "post_id" : NumberLong(2) } ] }
{ "user" : [ { "post_id" : NumberLong(4) } ] }
{ "user" : [ { "post_id" : NumberLong(5) } ] }
更好
{“用户”:[1,2,4,5}}
如何修改聚合查询
谢谢。您可以执行以下操作以获得所需: 1)
$unwind
用户数组
2) 使用$sort
对所有具有post\u id
3) 使用$group
作为聚合查询的下一个阶段,然后按user.post\u id
从所有文档中形成一个排序的user
数组:
db.user.aggregate([
{
'$match': {
'region': 'US',
}
},
{
'$lookup': {
'from': 'post',
'localField': 'user_id',
'foreignField': 'user_id',
'as': 'user'
}
},
{
$unwind : {
path : "$user",
preserveNullAndEmptyArrays : true
}
},
{
$sort : {
'user.post_id' : 1
}
},
{
$group : {
_id : null,
user : {
$push : "$user.post_id"
}
}
}
])
阅读更多关于和的信息。每个用户中是否只有一个
post\u id
?或者如果有多个,应如何进行排序?@RaviShankarBharti No每个用户都有多个post\u id
。但不管怎样,我必须按所有post\u id进行排序。如果每个用户有多个post,则排序不正确。因此,您希望对post\u id数组进行排序,并对聚合结果进行排序,对吗?如果一个用户文档中有多个post_id,你能举例说明你想要什么吗。准确地说,按post\u id
对所有文档进行排序。将路径选项扔到$unwind stage之前应该加上“$”:user“
errors。将$
添加到user,然后查询就可以工作了。但它还没有排序。它似乎只是使用数组的第一个元素进行排序。