如果数组包含值,Mongoose 查找文档

she*_*982 3 mongoose mongodb node.js

所以我有这个模式

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',
    }],
})
Run Code Online (Sandbox Code Playgroud)

我如何找到其类别数组包含给定 id 的文档?我的意思是像使用类别 id 获取所有文档的查询

Rus*_*aev 14

有一些方法可以实现这一目标。第一个是按$elemMatch操作员:

const docs = await Documents.find({category: { $elemMatch: {$eq: 'yourCategory'} }});
// you may need to convert 'yourCategory' to ObjectId
Run Code Online (Sandbox Code Playgroud)

第二个是 by$in$all运算符:

const docs = await Documents.find({category: { $in: [yourCategory] }});
Run Code Online (Sandbox Code Playgroud)

或者

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
Run Code Online (Sandbox Code Playgroud)

$in类似于 OR 和$allAND。有关更多详细信息,请检查此链接:https://docs.mongodb.com/manual/reference/operator/query/all/

第三个是按aggregate()功能:

const docs = await Documents.aggregate([
    { $unwind: '$category' },
    { $match: { 'category': mongoose.Types.ObjectId(yourCategory) } }
]};
Run Code Online (Sandbox Code Playgroud)

使用aggregate(),您只能在类别数组中获得一个类别ID。