$elemMatch operator in Mongoose

$elemMatch operator in Mongoose


The $elemMatch operator is useful when querying for documents that contain an array field with at least one element that matches multiple criteria. When you need to use multiple criteria then you need to mongoose $elemMatch

const mongoose = require('mongoose');
const { Schema } = mongoose;        
mongoose.connect('mongodb://127.0.0.1:27017/operators')  // connect with Mongodb I have cretaed the operators database in my Mongodb
    .then(() => {
        console.log('MongoDB connected')
    })
    .catch(err => console.log(err));        

const featureSchema = new Schema({
    name: String,
    version: Number,
    model: String,
    ratings: Number
});
        

const productSchema = new Schema({
    name: String,
    features: [featureSchema]
});
const Product = mongoose.model('Product', productSchema);
        

Each product can have many features. Now I would like to query for the products that have a Wifi feature, version should be greater than and model should be PC

Let's insert some dummy data:


const sampleProducts = [
    {
        name: 'Product1',
        features: [
            { name: 'WiFi', version: 5, model: 'Iphone', ratings: 5 },
            { name: 'Bluetooth', version: 4.2, model: 'Macbook', ratings: 5 }
        ]
    },
    {
        name: 'Product2',
        features: [
            { name: 'WiFi', version: 4, model: 'Android', ratings: 5 },
            { name: 'WiFi', version: 5, model: 'PC', ratings: 4 }
        ]
    }
];        
Product.insertMany(sampleProducts)
    .then(() => console.log('Sample products inserted'))
    .catch(err => console.log(err));        
Product.find({
    features: { $elemMatch: { name: 'WiFi', version: { $gte: 5 }, model: 'PC', ratings: { $gte: 4 } } }
}).then(products => {
    console.log(JSON.stringify(products));
});
        

I need to query based on multiple properties like name, version, model, and ratings. In that case you can use $elemMatch

Dot Notation

Product.find({
    "features.name": "WiFi",
    "features.version": { $gte: 5 },
    "features.ratings": { $gte: 4 },
    "features.model": "PC"
}).then(products => {
    console.log('2nd Result')
    console.log(JSON.stringify(products))
})        

There is another technique to query multiple arguments on the array. You can use the dot notation feature in MongoDB. features.name, `features.version` etc represent the dot nation

要查看或添加评论,请登录

社区洞察

其他会员也浏览了