Reputation: 33
so i have this schema
const Document = new mongoose.Schema({
_id:{
type:Number
},
creationDate:{
type:Date,
default:Date.now(),
},
title:String,
status:{
type:String,
default:status.PENDING
},
description: String,
category:[{
type:mongoose.Schema.Types.ObjectId,
ref:'Categories',
}],
})
how do i find documents that their category array contains an id given ? i mean like a query to get all documents using category id
Upvotes: 3
Views: 22488
Reputation: 497
There are some ways to achieve this.
First one is by $elemMatch
operator:
const docs = await Documents.find({category: { $elemMatch: {$eq: 'yourCategory'} }});
// you may need to convert 'yourCategory' to ObjectId
Second one is by $in
or $all
operators:
const docs = await Documents.find({category: { $in: [yourCategory] }});
or
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
is like OR and $all
like AND. For further details check this link : https://docs.mongodb.com/manual/reference/operator/query/all/
Third one is by aggregate()
function:
const docs = await Documents.aggregate([
{ $unwind: '$category' },
{ $match: { 'category': mongoose.Types.ObjectId(yourCategory) } }
]};
with aggregate() you get only one category id in your category array.
Upvotes: 14