首页 > 解决方案 > 如果数组包含值,猫鼬会查找文档

问题描述

所以我有这个架构

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',
    }],
})

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

标签: node.jsmongodbmongoose

解决方案


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

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

第二个是由$inor$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 和$allAND 一样。有关更多详细信息,请查看此链接:https ://docs.mongodb.com/manual/reference/operator/query/all/

第三个是按aggregate()功能:

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

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


推荐阅读