如何汇总与数组中匹配的值然后排序

问题描述

我有这些收藏夹:

lists
{_id: 1,item: "a",owner: 1}
users
{_id: 1,subs: [{_id: 1,active: "Y"},{_id: 2,active: "N"}]}
subs
{_id: 1,text: "A"}
{_id: 2,text: "B"}

我想要一个包含用户信息和有效的订阅者信息的列表的结果。

{_id: 1,owner: {_id: 1,subs: [{_id: {_id: 1,text: "A"},active: "Y"}]}}

我还想根据“文本”字段对其进行排序。

我尝试了汇总,但是失败了,

db.getCollection("lists").aggregate(
[
    { 
        "$lookup" : { 
            "from" : "users","localField" : "owner","foreignField" : "_id","as" : "owner"
        }
    },{ 
        "$match" : { 
            "owner.0.subs" : { 
                "$elemmatch" : { 
                    "active" : "Y"
                }
            }
        }
    }
],{ 
    "allowdiskUse" : false
}
);

我也使用猫鼬,但使用填充失败。 有什么办法可以得到我的结果吗?

在这里,我更新了聚合管道,

[
  {
    $lookup: {
      from: "users",as: "owner",let: { owner: "$owner" },pipeline: [
        { $match: { $expr: { $eq: ["$$owner","$_id"] } } },{ $unwind: { path:"$sub",preserveNullAndEmptyArrays: false} },{ $match: { "subs.active": "Y" } },{
          $lookup: {
            from: "plans",localField: "subs._id",foreignField: "_id",as: "subs.plans"
          }
        },{ $unwind: { path:"$subs.plans",]
    }
  },{ $unwind: { path: "$owner",preserveNullAndEmptyArrays: true} },{ '$sort': { item: 1 } },{ '$skip': 0 },{ '$limit': 20 } ]

解决方法

您可以将查询与管道和嵌套查询一起使用,

内部查找管道为:

  • $match您在用户集合中的所有者ID
  • $unwind解构subs数组,因为我们需要使用subs集合进行查找
  • $match订阅是否处于活动状态
  • $lookup(包含潜艇收藏)
  • $unwind解构我们从subs集合加入的subs._id
  • $group重建subs数组
  • $unwind解构owner数组
  • $sortitem$skip的分页
$limit

Playground


您的第二次编辑:在第一个$ unwind内的第一次查找中键名db.getCollection("lists").aggregate([ { $lookup: { from: "users",as: "owner",let: { owner: "$owner" },pipeline: [ { $match: { $expr: { $eq: ["$$owner","$_id"] } } },{ $unwind: "$subs" },{ $match: { "subs.active": "Y" } },{ $lookup: { from: "subs",localField: "subs._id",foreignField: "_id",as: "subs._id" } },{ $unwind: "$subs._id" },{ $group: { _id: "$_id",subs: { $push: { _id: "$subs._id._id",text: "$subs._id.text",active: "$subs.active" } } } } ] } },{ $unwind: "$owner" },{ $sort: { item: 1 } },{ $skip: 0 },{ $limit: 20 } ],{ allowDiskUse: false }) 错误,

sub

{ $unwind: { path:"$sub",preserveNullAndEmptyArrays: false} }

Your Working Query