mongo db在对象数组中过滤结果



产品模式有一个数组字段productDetails.

const ProductSchema = new Schema(
{
title: [{ lang: { type: String, upperCase: true }, value: String, _id: false }],
attributes: [
{
attributeGroup: { type: mongoose.Types.ObjectId, ref: 'AttributeGroup' },
att: [{ type: mongoose.Types.ObjectId, ref: 'Attribute' }]
}
],
shop: {
type: mongoose.Types.ObjectId,
ref: 'Shop'
},
promotion: {
percent: Number,
discountFrom: Date,
discountTo: Date
},
preparationTime: Number,
description: [{ lang: { type: String, upperCase: true }, value: String, _id: false }],
photoUrl: [String],
productDetails: [
{
size: {
enum: ['SMALL', 'MEDIUM', 'LARGE'],
type: String
},
price: Number,
stock: { type: Number, min: 0, default: 0 },
afterDiscountPrice: Number
}
],
reqCarTypes: [
{
type: mongoose.Types.ObjectId,
ref: 'ReqCarType'
}
],
isDeleted: { type: Boolean, default: false }
},
{ timestamps: true }
)

例如,我有一个这样的产品文档:

{
"_id" : ObjectId("60aa201525d6cd24d873d5dc"),
"photoUrl" : [ 
"http://lorempixel.com/640/480", 
"http://lorempixel.com/640/480"
],
"reqCarTypes" : [],
"isDeleted" : false,
"shop" : null,
"promotion" : {
"percent" : 36,
"discountFrom" : ISODate("2021-01-23T09:27:49.623Z"),
"discountTo" : ISODate("2021-12-25T09:27:49.624Z")
},
"title" : [],
"attributes" : [],
"description" : [],
"productDetails" : [ 
{
"price" : 40,
"afterDiscountPrice" : 12,
"_id" : ObjectId("60aa201525d6cd24d873d5dc"),
"size" : "SMALL"
}, 
{
"price" : 50,
"afterDiscountPrice" : 12,
"_id" : ObjectId("61aa201525d6cd24d873d5dc"),
"size" : "MEDIUM"
}
],
"createdAt" : ISODate("2021-05-23T09:27:49.641Z"),
"updatedAt" : ISODate("2021-05-23T09:27:49.641Z"),
"__v" : 0
}

那么我希望返回所有字段,除了那些我没有设置productDetails id的字段。

我可以从前端获得productDetails id,我希望返回这样的东西:

{
"_id" : ObjectId("60aa201525d6cd24d873d5dc"),
"photoUrl" : [ 
"http://lorempixel.com/640/480", 
"http://lorempixel.com/640/480"
],
"reqCarTypes" : [],
"isDeleted" : false,
"shop" : null,
"promotion" : {
"percent" : 36,
"discountFrom" : ISODate("2021-01-23T09:27:49.623Z"),
"discountTo" : ISODate("2021-12-25T09:27:49.624Z")
},
"title" : [],
"attributes" : [],
"description" : [],
"productDetails" : [ 
{
"price" : 40,
"afterDiscountPrice" : 12,
"_id" : ObjectId("60aa201525d6cd24d873d5dc"),
"size" : "SMALL"
}
],
"createdAt" : ISODate("2021-05-23T09:27:49.641Z"),
"updatedAt" : ISODate("2021-05-23T09:27:49.641Z"),
"__v" : 0
}

查看productDetails字段。我使用nodejs和typescript。

我认为这个查询将适用于您的集合,并根据我的理解给出您想要的结果

db.collection.aggregate
([
{$match:{_id:PRODUCT_ID}},
{$project:{
_id:'$_id',
productDetails:{
$filter: {
input: "$productDetails",
as: "productDetails",
cond: { $eq: [ "$$productDetails._id", PRODUCT_ID ] }
}
},
photoUrl :"$photoUrl",
reqCarTypes : "$reqCarTypes",
isDeleted : "$isDeleted",
shop : "$shop",
promotion : "$promotion",
title : "$title",
attributes : "$attributes",
description : "$description",
createdAt : "$createdAt",
updatedAt :"$updatedAt",
}},
])

最新更新