これを実現する方法はいくつかあります。最初の方法は$elemMatchです。 演算子:
const docs = await Documents.find({category: { $elemMatch: {$eq: 'yourCategory'} }});
// you may need to convert 'yourCategory' to ObjectId
2つ目は$inによるものです または$all 演算子:
const docs = await Documents.find({category: { $in: [yourCategory] }});
または
const docs = await Documents.find({category: { $all: [yourCategory] }});
// you can give more categories with these two approaches
//and again you may need to convert yourCategory to ObjectId
$in ORと$allのようなものです ANDのように。詳細については、次のリンクを確認してください: https://docs.mongodb.com / manual / reference / operator / query / all /
3つ目はaggregate()によるものです 機能:
const docs = await Documents.aggregate([
{ $unwind: '$category' },
{ $match: { 'category': mongoose.Types.ObjectId(yourCategory) } }
]};
アグリゲート()を使用すると、カテゴリ配列で取得できるカテゴリIDは1つだけです。