How to implement according to the array by aggregating ordered by qualified field

i have the data need SortNo sorting for different sorts.id:

{
    "_id": "bac62c07d4bc49a0a6e2884483aced1c",
    "sorts": [
        {
            "id": "t1",
            "sortNo": 1
        },
       {
            "id": "t2",
            "sortNo": 3
        }
    ]
}


{
    "_id": "bac62c07d4bc49a0a6e2884483aced13",
    "sorts": [
        {
            "id": "t1",
            "sortNo": 3
        },
       {
            "id": "t2",
            "sortNo": 1
        }
    ]
}

I have a more complex implementation scheme:


db.getCollection("test").aggregate([
    {
        $unwind: "$sorts"
    },
    {
        $match: {
            "sorts.id": "t1"
        }
    },
    {
        $sort: {
            "sorts.sortNo": 1
        }
    },
    {
        $project: {
            "_id": 1
        }
    },
    {
        $lookup: {
            "from": "test",
            "as": "list",
            "foreignField": "_id",
            "localField": "_id"
        }
    },
    {
        $unwind: "$list"
    },
    {
        "$replaceRoot": {
            "newRoot": "$list"
        }
    }
])

I want to know whether it is possible to directly use the simple find method??

Hi @1111027 ,

Not sure I fully understand the needed output.

Can you share how would the output look like?

Are you trying to sort the _id by the inner arrays or you want to sort the arrays?

Thanks
Pavel

I do not see any differences in the output you supplied.

sorry,i Input error!
sort: “sorts.sortNo”: 1

if match: “sorts.id”: “t1”
well get results:
“_id”: “bac62c07d4bc49a0a6e2884483aced1c”,…
“_id”: “bac62c07d4bc49a0a6e2884483aced13”,…

if match:“sorts.id”: “t2”:
“_id”: “bac62c07d4bc49a0a6e2884483aced13”,…
“_id”: “bac62c07d4bc49a0a6e2884483aced1c”,…

I really do not understand this.

And why don’t you simply have documents like:

{
    "_id": "bac62c07d4bc49a0a6e2884483aced1c",
    "sorts": { t1 : 1 , t2 : 3 }
}
{
    "_id": "bac62c07d4bc49a0a6e2884483aced13",
    "sorts": { t1: 3 , t2 : 1 }
}

and do

db.test.find( { "sorts.t1" : { "$exists" : true } } ).sort( "sorts.t1" ).projection( { _id : 1 } )

Because in actual business, t1 and t2 are not always fixed, and there may be t3, t4… and so on. We want to achieve this through array data expansion rather than through extended fields. In this way, you can have a more fixed and scalable data model

It looks like you are somehow implementing the attribute pattern.

One way I could see how you could do that is with the following.

1 - a $set stage that uses $filter to extract the sorts needed
2 - a $match stage that removes document where $filter did not find a sorts to use
3 - a $set stage that uses the result of the $filter to set a top level sortNo