这是我的桌子:
{
"_id" : ObjectId("5f2e8e0d4976ed2c04fc2e90"),
"reference" : "5f2e8e0d4976ed2c04fc2e8f",
"id" : "5e87187f6e8c15766e6994f8",
"name" : "no name",
"items" : [
{
"_id" : ObjectId("5f2e994336caf138c13560fc"),
"requestedItems" : "5e87187f6e8c15766e6994f8",
"name" : "no name",
},
{
"_id" : ObjectId("5f2e994336caf138c135601c"),
"requestedItems" : "5e87187f6e8c15766e6994f8",
"name" : "no name",
},
{
"_id" : ObjectId("5f2e994336caf138c135201c"),
"requestedItems" : "5e87187f6e8c15766e6994f8",
"name" : "no name",
},
{
"_id" : ObjectId("5f2e994336caf138c139521c"),
"requestedItems" : "5e87187f6e8c15766e6994f8",
"name" : "no name",
},
{
"_id" : ObjectId("5f2e994336caf138c139504f"),
"requestedItems" : "5e87187f6e8c15766e6994f8",
"name" : "no name",
},
],
"createdAt" : ISODate("2020-08-08T11:35:41.675Z"),
"updatedAt" : ISODate("2020-08-18T13:34:43.077Z"),
"date" : "8-8-2020",
"__v" : 0
}
我只想查询“ITEMS”中的最后三个子文档,我一直在尝试 MongoDB 聚合框架,但没有成功。这是我想出的。任何帮助将不胜感激。
reqInventory.aggregate([
{$match:{"id" : "5e87187f6e8c15766e6994f8"}},
{ $addFields: {
items: {
$map: {
input: '$items',
as: 'new',
in: {
requestedItems : '$$new.requestedItems',
name : '$$new.name',
items: { $slice: [ '$$new.items', 3 ] }
}
}
}
}}