假设我有一个聚合管道,我可以根据需要获得所需的详细信息,但我需要按降序排序名为visits
的键的值,然后在其中选择条目。
{
$match: {
mobile_number: "1234567890",
}
},
{
$lookup: {
from: "visitor_logs",
localField: "_id",
foreignField: "visitor_id",
as: "visits",
}
},
{
$project: {
_id: 0,
visitor_id: "$_id",
first_name: "$first_name",
last_name: "$last_name",
mobile_number: "$mobile_number",
visits: {
$filter: {
input: "$visits",
as: "visit",
cond: {
$and: [
{$gte: ["$$visit.in_time", "1610609615"]},
{$lte: ["$$visit.in_time", "1610615328"]},
]
}
},
},
}
},
]);
样品响应
{
"type": "SUCCESS",
"log": [
{
"visitor_id": "5ffff1354351be2c600c4f94",
"first_name": "Ayan",
"last_name": "Dey",
"mobile_number": "1234567890",
"visits": [
{
"_id": "5ffff3df82dc1a0e90d89a5c",
"in_time": "1610609615",
"out_time": "1610609671",
"checked_in_status": false,
"visitor_id": "5ffff1354351be2c600c4f94",
"visit_purpose": "Test",
"person_to_meet": "Someone new",
"__v": 0
},
{
"_id": "5ffff41a82dc1a0e90d89a5d",
"in_time": "1610609615",
"out_time": "1610609730",
"checked_in_status": false,
"visitor_id": "5ffff1354351be2c600c4f94",
"visit_purpose": "Test",
"person_to_meet": "Someone new",
"__v": 0
},
{
"_id": "5ffff45a82dc1a0e90d89a5e",
"in_time": "1610609615",
"out_time": "1610609919",
"checked_in_status": false,
"visitor_id": "5ffff1354351be2c600c4f94",
"visit_purpose": "Test",
"person_to_meet": "Someone new",
"__v": 0
}
]
}
]
}
现在,我要寻找的是基于visits
按降序排列_id
字段。我的意思是,在visits
中只选择特定的项目。
发布于 2021-01-15 09:46:35
希望您已经解决了,这可能对您有所帮助,请尝试用管道查找,
let
通过本地字段,管道将条件放置在$match
阶段,过滤条件在$project
阶段不需要过滤。并将排序按_id
降序排列 { $match: { mobile_number: "1234567890", } },
{
$lookup: {
from: "visitor_logs",
let: { visitor_id: "$_id" },
pipeline: [
{
$match: {
$expr: { $eq: ["$$visitor_id", "$visitor_id"] },
in_time: {
$gte: "1610609615",
$lte: "1610615328"
}
}
},
{ $sort: { _id: -1 } },
{
$project: {
_id: 0,
v_id: "$_id",
in_time: 1,
out_time: 1,
checked_in_status: 1,
visit_purpose: 1,
person_to_meet: 1
}
}
],
as: "visits"
}
},
{
$project: {
_id: 0,
visitor_id: "$_id",
first_name: 1,
last_name: 1,
mobile_number: 1,
visits: 1
}
}
发布于 2021-01-15 08:20:09
其中一种方法是使用unwind
- 玩。
db.collection.aggregate([
{//de-normalize
"$unwind": "$log"
},
{//de-normalize
"$unwind": "$log.visits"
},
{//sort
"$sort": {
"log.visits._id": -1
}
}
])
然后,您可以根据您的摘樱桃逻辑添加$match
或$project
。
在采摘樱桃之后,您可以使用$group
将数据重塑为问题婴儿中的格式。
您可以再次按抽样这里进行分组。
{
$group: {
_id: "$categoryData._id",
count: {
$sum: 1
},
total_price: {
$sum: "$asset_price"
}
}
}
https://stackoverflow.com/questions/65732364
复制相似问题