1111027
(和利 张)
December 9, 2022, 5:25am
#1
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
steevej
(Steeve Juneau)
December 9, 2022, 2:30pm
#4
I do not see any differences in the output you supplied.
1111027
(和利 张)
December 12, 2022, 2:00am
#5
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”,…
steevej
(Steeve Juneau)
December 12, 2022, 10:48pm
#6
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 } )
1111027
(和利 张)
December 19, 2022, 3:06am
#7
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
steevej
(Steeve Juneau)
December 19, 2022, 2:20pm
#8
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