Sort and Count query method using mongoose
Count Query
const mongoose = require('mongoose');mongoose.connect("mongodb://localhost:27017/newDB",{useNewUrlParser: true}).then(()=>{console.log("connction successful...")}).catch((err)=>console.log(err));const playlistSchema = new mongoose.Schema ({// define schemaname:{type : String,required : true},sirname : String,email : String,role : String,active : Boolean,date : {type: Date,default : Date.now},roll : Number,})// collection creation// in model("collection name", define schema)const PlayList = new mongoose.model("PlayList",playlistSchema)// get all data inside Databaseconst getDocument = async()=>{try {const result = await PlayList.find({role : "front-end"}).select({name:1}).countDocuments();console.log(result);}catch(err){console.log(err);}}getDocument();
connction successful... 4Sort Query
const getDocument = async () => {try {const result = await PlayList.find({ role: "front-end" }).select({ name: 1 }).sort("name : 1"); //1 means assending orderconsole.log(result);} catch (err) {console.log(err);}}getDocument();
connction successful... [ { _id: new ObjectId("61cc0946c62a51adf6bc23dc"), name: 'Amit' }, { _id: new ObjectId("61cc0946c62a51adf6bc23db"), name: 'Omkar' }, { _id: new ObjectId("61cc0946c62a51adf6bc23d9"), name: 'Shreyash' }, { _id: new ObjectId("61cc0946c62a51adf6bc23da"), name: 'Vaibhav' } ]another Example
const getDocument = async () => {try {const result = await PlayList.find({ role: "front-end" }).select({ roll: 1 }).sort({roll: 1}); //1 means assending order -1 means dessendingconsole.log(result);} catch (err) {console.log(err);}}getDocument();
connction successful... [ { _id: new ObjectId("61cc0946c62a51adf6bc23db"), roll: 383 }, { _id: new ObjectId("61cc0946c62a51adf6bc23d9"), roll: 483 }, { _id: new ObjectId("61cc0946c62a51adf6bc23da"), roll: 583 }, { _id: new ObjectId("61cc0946c62a51adf6bc23dc"), roll: 683 } ]
Post a Comment