我正在使用mongoose和node js进行开发。 我想要从嵌入式文档$pull
最近的对象spas
。
这是我的样本数据。 请帮我构建mongodb查询。
{
"_id" : ObjectId("5f071322c89b0e2a7c35a25a"),
"totalPrice" : 0,
"user" : ObjectId("5ee096ee7febd3408828ce2c"),
"type" : "SpaService",
"spas" : [
{
"price" : 0,
"_id" : ObjectId("5f071322c89b0e2a7c35a25b"),
"categoryId" : ObjectId("5ebbfd29b117f50dac1039e2"),
"serviceId" : ObjectId("5ebbfd29b117f50dac1039e3"),
"duration" : 60
},
{
"price" : 0,
"_id" : ObjectId("5f071328c89b0e2a7c35a25c"),
"categoryId" : ObjectId("5ebbfd29b117f50dac1039e2"),
"serviceId" : ObjectId("5ebbfd29b117f50dac1039e3"),
"duration" : 60
},
{
"price" : 0,
"_id" : ObjectId("5f071363c89b0e2a7c35a25d"),
"categoryId" : ObjectId("5ebbfd29b117f50dac1039e2"),
"serviceId" : ObjectId("5ebbfd29b117f50dac1039e3"),
"duration" : 30
}
],
"listingId" : ObjectId("5ebbf95fb117f50dac1039d1")
}
在本例中,我在spas
中有3个object
,我希望拉取最近的_id
,其duration
为60。 请帮帮我。
db.test.aggregate([
{
"$match": {
"spas.duration": 60
}
},
{$project: {
spas: {$filter: {
input: '$spas',
as: 'spas',
cond: {$eq: ['$$spas.duration', 60]}
}}
}},
{$unwind: {path: "$spas"}},
{$sort: {"spas._id": -1}},
{$group: {_id: "$_id", data: {$first: "$$ROOT"}}},
])
它返回
/* 1 */
{
"_id" : ObjectId("5f071322c89b0e2a7c35a25a"),
"data" : {
"_id" : ObjectId("5f071322c89b0e2a7c35a25a"),
"spas" : {
"price" : 0,
"_id" : ObjectId("5f071328c89b0e2a7c35a25c"),
"categoryId" : ObjectId("5ebbfd29b117f50dac1039e2"),
"serviceId" : ObjectId("5ebbfd29b117f50dac1039e3"),
"duration" : 60
}
}
}
它在做什么: