简体   繁体   中英

mongodb regex how to match image/*

I've got a schema like

var MediaSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    user: {
        type: String,
        default: 'whisher',
        trim: true
    },
    title: {
        type: String,
        default: '',
        trim: true
    },
    type: {
        type: String,
        default: '',
        trim: true
    },
    url: {
        type: String,
        default: '',
        trim: true
    }
});

in type I can have

image/gif:

image/jpeg:

image/pjpeg:

image/png:

image/svg+xml:

image/example:

but also

application/pdf

video/mpeg

and so on

my goal is fetch all the rows which are images so I tried with:

db.media.find( { type: /image/gif|jpeg|pjpeg|png/i } );

but give me

SyntaxError: Invalid flags supplied to RegExp constructor 'gif'

so what's the right way ? Is there a better way of querying without using regex ?

You can use $regex operator as follows :

db.collection.find({type : {$regex : "^image/.*", $options : "i"}})

You can also query without using $regex operator as follows :

db.collection.find({type : /.*image.*/i})

If this query is frequent, I'd recommend you add a new field that more closely maps to your requirement:

isImage : Boolean

Or, a bit more general if you'd like:

typeGroup: Number

You would index either one. typeGroup might be set to a 1 for example if it was an image of any type, or 2 if it was a video file, etc.

Performing a regular expression to match the files repeatedly to answer the same question will measurably affect the overall performance of your application. With this alternative approach, you can easily find the correct documents efficiently:

Media.find().where('isImage', true).exec(/* your callback */);
db.media.find( { type: /image\/gif|jpeg|pjpeg|png/i } ); 

但是还有更好的方法吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM