3

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

sherlocked982
  • 33
  • 1
  • 1
  • 5
  • You can try using the array query operator [$elemMatch](https://docs.mongodb.com/v4.2/reference/operator/query/elemMatch/). – prasad_ Aug 12 '20 at 01:44
  • Does this answer your question? [Find document with array that contains a specific value](https://stackoverflow.com/questions/18148166/find-document-with-array-that-contains-a-specific-value) – Black Mamba Aug 12 '20 at 05:15

1 Answers1

14

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.