Lets say I have an aggregation pipeline, and I am being able to get the required details as needed but I need to sort values of key named visits
in descending order and then cherry pick items in it.
JavaScript
x
36
36
1
{
2
$match: {
3
mobile_number: "1234567890",
4
}
5
},
6
{
7
$lookup: {
8
from: "visitor_logs",
9
localField: "_id",
10
foreignField: "visitor_id",
11
as: "visits",
12
}
13
},
14
{
15
$project: {
16
_id: 0,
17
visitor_id: "$_id",
18
first_name: "$first_name",
19
last_name: "$last_name",
20
mobile_number: "$mobile_number",
21
visits: {
22
$filter: {
23
input: "$visits",
24
as: "visit",
25
cond: {
26
$and: [
27
{$gte: ["$$visit.in_time", "1610609615"]},
28
{$lte: ["$$visit.in_time", "1610615328"]},
29
]
30
}
31
},
32
},
33
}
34
},
35
]);
36
Sample response
JavaScript
1
44
44
1
{
2
"type": "SUCCESS",
3
"log": [
4
{
5
"visitor_id": "5ffff1354351be2c600c4f94",
6
"first_name": "Ayan",
7
"last_name": "Dey",
8
"mobile_number": "1234567890",
9
"visits": [
10
{
11
"_id": "5ffff3df82dc1a0e90d89a5c",
12
"in_time": "1610609615",
13
"out_time": "1610609671",
14
"checked_in_status": false,
15
"visitor_id": "5ffff1354351be2c600c4f94",
16
"visit_purpose": "Test",
17
"person_to_meet": "Someone new",
18
"__v": 0
19
},
20
{
21
"_id": "5ffff41a82dc1a0e90d89a5d",
22
"in_time": "1610609615",
23
"out_time": "1610609730",
24
"checked_in_status": false,
25
"visitor_id": "5ffff1354351be2c600c4f94",
26
"visit_purpose": "Test",
27
"person_to_meet": "Someone new",
28
"__v": 0
29
},
30
{
31
"_id": "5ffff45a82dc1a0e90d89a5e",
32
"in_time": "1610609615",
33
"out_time": "1610609919",
34
"checked_in_status": false,
35
"visitor_id": "5ffff1354351be2c600c4f94",
36
"visit_purpose": "Test",
37
"person_to_meet": "Someone new",
38
"__v": 0
39
}
40
]
41
}
42
]
43
}
44
Now, what I am looking for is to arrange the visits
field in descending order based on _id
. And by cherry-picking I mean, selecting only certain items inside visits
.
Advertisement
Answer
Hope you have resolved, for the reference this may help you, try lookup with pipeline,
let
to pass localfield, pipeline to put your conditions in$match
stage and your filter conditions you don’t need to filter in$project
stage. and put sort by_id
in descending order
JavaScript
1
42
42
1
{ $match: { mobile_number: "1234567890", } },
2
{
3
$lookup: {
4
from: "visitor_logs",
5
let: { visitor_id: "$_id" },
6
pipeline: [
7
{
8
$match: {
9
$expr: { $eq: ["$$visitor_id", "$visitor_id"] },
10
in_time: {
11
$gte: "1610609615",
12
$lte: "1610615328"
13
}
14
}
15
},
16
{ $sort: { _id: -1 } },
17
{
18
$project: {
19
_id: 0,
20
v_id: "$_id",
21
in_time: 1,
22
out_time: 1,
23
checked_in_status: 1,
24
visit_purpose: 1,
25
person_to_meet: 1
26
}
27
}
28
],
29
as: "visits"
30
}
31
},
32
{
33
$project: {
34
_id: 0,
35
visitor_id: "$_id",
36
first_name: 1,
37
last_name: 1,
38
mobile_number: 1,
39
visits: 1
40
}
41
}
42