Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

query builder in node js

How to get random question

const feedbacks = await QuestionModel.aggregate([{ $sample: { size: 1 } }]);

Image description

How to get random question based on permission

Image description

Image description

How to get all data

const questions = await QuestionModel.find({})
Enter fullscreen mode Exit fullscreen mode

How to get single data

 const existingUser = await FeedbackModel.findOne({ email });
  const existingquestion = await FeedbackModel.findOne({ questionid });
Enter fullscreen mode Exit fullscreen mode

How to get all objectsid and questionid of multiple objects
from collections where specific mail matched

  const users = await FeedbackModel.find({ email:id }, { questionid: 1 });
Enter fullscreen mode Exit fullscreen mode

How to get all question id of multiple objects of multiple collections where specific mail matched

  const users = await FeedbackModel.find({ email:id }, { questionid: 1 });

  const questionIds = users.map((user) => user.questionid);
Enter fullscreen mode Exit fullscreen mode

How to get single objects of collections where following array of question is not present

const feedback = await QuestionModel.findOne({ questionid: { $nin: questionIds } });
Enter fullscreen mode Exit fullscreen mode

How to count all row from single collection

const length = await QuestionModel.countDocuments()
Enter fullscreen mode Exit fullscreen mode

How to save or insert the data in node js

const result = await QuestionModel.create(values)
Enter fullscreen mode Exit fullscreen mode

Fetches the last (most recent)/latest document from the collection

const lastObject = await QuestionModel.findOne().sort({ _id: -1 }).exec()
Enter fullscreen mode Exit fullscreen mode

How to Update data

const updatedClient = await QuestionModel.findByIdAndUpdate(_id, values, {
  new: true,
})
Enter fullscreen mode Exit fullscreen mode
const { Question,  answerone, answertwo, answerthree, answerfour,checkone,checktwo,checkthree,checkfour,textanswer,email,userId,questionid} =
  req.body
const myanswer=checkone?'answerone' + "-" + checkone:checktwo?'answertwo' + "-" + checktwo:checkthree?'answerthree' + "-" + checkthree:'answerfour' + "-" + checkfour;
 const existingq = await FeedbackModel.findOne({ questionid });
          console.log(existingq);

            if(existingq)
            {
            existingq.checkone=[... existingq.checkone,myanswer]
            existingq.email=[... existingq.email,email]
            existingq.textanswer=[... existingq.textanswer,textanswer]
            feedback= await FeedbackModel.findByIdAndUpdate(existingq._id,existingq,{new:true})
          console.log(feedback)
                  res.status(200).json({ feedback }) 
                }

Enter fullscreen mode Exit fullscreen mode

How to get data where more than one condition matched

const clientAlreadyExist = await ClientModel.find({
    email: email,
    company_name: companyName,
  })
Enter fullscreen mode Exit fullscreen mode
const questionsList = await QuestionModel.find({
  createdAt: {
    $gte: startDateTime,
    $lte: endDateTime,
  },
}).select("question questionid -_id");
Enter fullscreen mode Exit fullscreen mode
  const feedback = await QuestionModel.findOne({
  $and: [
    { questionid: { $nin: questionIds } },
    { permission: 1 }
  ]
         });
Enter fullscreen mode Exit fullscreen mode

How to count the all no of objects from collection where some particular condition matched

const totalUser = await ClientModel.countDocuments(query)
Enter fullscreen mode Exit fullscreen mode

Counting the number of products with a specific category:

const count = await ProductModel.countDocuments({ category: 'electronics' });
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of users with a specific role:

const count = await UserModel.countDocuments({ role: 'admin' });
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of orders with a specific status:

const count = await OrderModel.countDocuments({ status: 'completed' });
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of books published in a specific year:

const count = await BookModel.countDocuments({ year: 2022 });
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of customers with a specific age range:

const count = await CustomerModel.countDocuments({ age: { $gte: 18, $lte: 30 } });
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of posts with a specific tag:

const count = await PostModel.countDocuments({ tags: 'technology' });
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of students enrolled in a specific course:

const count = await EnrollmentModel.countDocuments({ course: 'mathematics' });
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of products with a price greater than a certain value:

const count = await ProductModel.countDocuments({ price: { $gt: 100 } });
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of tasks assigned to a specific user:

const count = await TaskModel.countDocuments({ assignedTo: 'John Doe' });
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of comments with a specific word in the content:

const count = await CommentModel.countDocuments({ content: /great/ });
console.log(count);
Enter fullscreen mode Exit fullscreen mode

OR Operator

Counting the number of products with either category "electronics" or "clothing":

const count = await ProductModel.countDocuments({
  $or: [{ category: 'electronics' }, { category: 'clothing' }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of users with either role "admin" or "manager":

const count = await UserModel.countDocuments({
  $or: [{ role: 'admin' }, { role: 'manager' }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of orders with either status "completed" or "shipped":

const count = await OrderModel.countDocuments({
  $or: [{ status: 'completed' }, { status: 'shipped' }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of books published either in the year 2022 or 2023:

const count = await BookModel.countDocuments({
  $or: [{ year: 2022 }, { year: 2023 }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of customers with either age greater than 30 or less than 18:

const count = await CustomerModel.countDocuments({
  $or: [{ age: { $gt: 30 } }, { age: { $lt: 18 } }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of posts with either tag "technology" or "science":

const count = await PostModel.countDocuments({
  $or: [{ tags: 'technology' }, { tags: 'science' }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of students enrolled either in the course "mathematics" or "physics":

const count = await EnrollmentModel.countDocuments({
  $or: [{ course: 'mathematics' }, { course: 'physics' }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of products with either price greater than 100 or less than 50:

const count = await ProductModel.countDocuments({
  $or: [{ price: { $gt: 100 } }, { price: { $lt: 50 } }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of tasks assigned to either "John Doe" or "Jane Smith":

const count = await TaskModel.countDocuments({
  $or: [{ assignedTo: 'John Doe' }, { assignedTo: 'Jane Smith' }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of comments with either word "great" or "awesome" in the content:

const count = await CommentModel.countDocuments({
  $or: [{ content: /great/ }, { content: /awesome/ }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

and operataor

Counting the number of products with category "electronics" and price greater than $500:

const count = await ProductModel.countDocuments({
  $and: [{ category: 'electronics' }, { price: { $gt: 500 } }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of users with role "admin" and age greater than 25:

const count = await UserModel.countDocuments({
  $and: [{ role: 'admin' }, { age: { $gt: 25 } }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

Counting the number of orders with status "completed" and total amount greater than $1000:

const count = await OrderModel.countDocuments({
  $and: [{ status: 'completed' }, { totalAmount: { $gt: 1000 } }]
});
console.log(count);
Enter fullscreen mode Exit fullscreen mode

use of skip and limit

 const clients = await ClientModel.find(query).skip(startIndex).limit(limit)
Enter fullscreen mode Exit fullscreen mode

Get the first 10 users:

const users = await UserModel.find().limit(10);
console.log(users);
Enter fullscreen mode Exit fullscreen mode

Get the next 10 users after skipping the first 10:

const users = await UserModel.find().skip(10).limit(10);
console.log(users);
Enter fullscreen mode Exit fullscreen mode

Get the first 5 products in the "electronics" category:

const products = await ProductModel.find({ category: "electronics" }).limit(5);
console.log(products);
Enter fullscreen mode Exit fullscreen mode

Get the next 5 products in the "electronics" category after skipping the first 5:

const products = await ProductModel.find({ category: "electronics" }).skip(5).limit(5);
console.log(products);
Enter fullscreen mode Exit fullscreen mode

Get the first 20 orders with a status of "completed":

const orders = await OrderModel.find({ status: "completed" }).limit(20);
console.log(orders);
Enter fullscreen mode Exit fullscreen mode

Get the next 20 orders with a status of "completed" after skipping the first 20:

const orders = await OrderModel.find({ status: "completed" }).skip(20).limit(20);
console.log(orders);
Enter fullscreen mode Exit fullscreen mode

Get the first 50 posts created by the user with the ID "12345":

const posts = await PostModel.find({ createdBy: "12345" }).limit(50);
console.log(posts);
Enter fullscreen mode Exit fullscreen mode

Get the next 50 posts created by the user with the ID "12345" after skipping the first 50:

const posts = await PostModel.find({ createdBy: "12345" }).skip(50).limit(50);
console.log(posts);
Enter fullscreen mode Exit fullscreen mode

Get the first 100 comments with a rating greater than 4:

const comments = await CommentModel.find({ rating: { $gt: 4 } }).limit(100);
console.log(comments);
Enter fullscreen mode Exit fullscreen mode

Get the next 100 comments with a rating greater than 4 after skipping the first 100:

const comments = await CommentModel.find({ rating: { $gt: 4 } }).skip(100).limit(100);
console.log(comments);
Enter fullscreen mode Exit fullscreen mode

How to update in collection

const updatedClient = await ClientModel.findByIdAndUpdate(_id, values, {
    new: true,
  })
Enter fullscreen mode Exit fullscreen mode

How to select some particulars object from collections

const client = await ClientModel.find({}).select("company_name -_id")
Enter fullscreen mode Exit fullscreen mode
 const users = await User.find({ role: "developer" }).select("_id email name")
Enter fullscreen mode Exit fullscreen mode

How to find by id or objectid

 const worklog = await Worklog.findById(id)
  const project = await Project.findById(worklog.projectId)
  const task = await Task.findById(worklog.taskId)
Enter fullscreen mode Exit fullscreen mode

How to delete by id

const deletedWorklog = await Worklog.findByIdAndDelete(id)
Enter fullscreen mode Exit fullscreen mode

How to extract array value from key value pair

const role = { questionId: 6 };
const questionId = role.questionId;
console.log(questionId); // Output: 6
Enter fullscreen mode Exit fullscreen mode

How to insert or update single field in multiple object of single collection
How to get single field in multiple object of single collection
How to count no of object where particular condition staisfied

Image description

How to insert or update single field in single object of single collection
How to get single object where some condition matched collection

Image description

More Example of updateone and updatemany

const YourModel = require('./YourModel'); // Import your Mongoose model

const insertNewField = async () => {
  try {
    await YourModel.updateMany({ role: 'admin' }, { $set: { newField: 'value' } });
    console.log('New field inserted successfully.');
  } catch (error) {
    console.error('Error inserting new field:', error);
  }
};

insertNewField();

Enter fullscreen mode Exit fullscreen mode
const YourModel = require('./YourModel'); // Import your Mongoose model

const insertNewField = async () => {
  try {
    await YourModel.updateOne({ role: 'admin' }, { $set: { newField: 'value' } });
    console.log('New field inserted successfully.');
  } catch (error) {
    console.error('Error inserting new field:', error);
  }
};

insertNewField();

Enter fullscreen mode Exit fullscreen mode

const updatedFields = {
  field1: 'value1',
  field2: 'value2',
  field3: 'value3'
};
  const filter = { questionId: 6 };
  const update = { $set: updatedFields };

  const result = await YourModel.updateOne(filter, update);


Enter fullscreen mode Exit fullscreen mode
const insertNewField = async () => {
  try {
    await YourModel.updateOne({ questionId: 6 }, { $set: { newField: 'value' } });
    console.log('New field inserted successfully.');
  } catch (error) {
    console.error('Error inserting new field:', error);
  }
};

insertNewField();
Enter fullscreen mode Exit fullscreen mode
const YourModel = require('./YourModel'); // Import your Mongoose model

const insertNewField = async (role) => {
  try {
    await YourModel.updateOne(role, { $set: { newField: 'value' } });
    console.log('New field inserted successfully.');
  } catch (error) {
    console.error('Error inserting new field:', error);
  }
};

const role = { questionId: 6 };
insertNewField(role);
Enter fullscreen mode Exit fullscreen mode
const YourModel = require('./YourModel'); // Import your Mongoose model

const insertNewField = async () => {
  try {
    const filter = { questionId: 6 };
    const update = { newField: 'value' };

    await YourModel.findOneAndUpdate(filter, update);
    console.log('New field inserted successfully.');
  } catch (error) {
    console.error('Error inserting new field:', error);
  }
};

insertNewField();
Enter fullscreen mode Exit fullscreen mode
const YourModel = require('./yourModel'); // Replace with your model

const fieldName = 'newField';
const fieldValue = 'newValue';

// Update documents that don't have the new field
YourModel.updateMany(
  { newField: { $exists: false } },
  { $set: { [fieldName]: fieldValue } },
  (err, result) => {
    if (err) {
      console.error(err);
    } else {
      console.log(`${result.nModified} documents updated`);
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

left join or aggregate operator


 const myfeedback = await FeedbackModel.aggregate([
        {
          $match: { questionid: number }
        },
        {
          $lookup: {
            from: 'users', 
            localField: 'email',
            foreignField: 'email',
            as: 'joinedData'
          }
        },
        {
          $addFields: {
            name: { $arrayElemAt: ['$joinedData.name', 0] }
            // Replace 'fieldName' with the actual field name from the 'users' collection you want to include
          }
        }
        // {
        //   $project:{
        //     joinedData:1
        //   }
        // }
      ]);  
      console.log(myfeedback); 
      const mydata = await FeedbackModel.find({ questionid: item }, { email: 1, _id: 0 }).exec();
     const emails = mydata.map((obj) => obj.email);
      console.log(emails);    
      const feedbacks = await User.find({ email: { $in: emails } }, { name: 1, _id: 0 }).exec();
      const feedback = feedbacks.map((obj) => obj.name);
      console.log(feedback);
      res.status(200).json({ myfeedback ,feedback: feedback})
Enter fullscreen mode Exit fullscreen mode
const getAlluserTicket = async (req, res) => {
  // const tickets = await Ticket.find({ closed: false })
  console.log("all tickets")
  console.log(req.user._id,)
  try {
    const searchQuery = req.query.search || ""
    const query = { company_name: { $regex: searchQuery, $options: "i" } }
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 10
    const startIndex = (page - 1) * limit
    const lastIndex = page * limit
    const totalUser = await Ticket.countDocuments(query)
    const pageCount = Math.ceil(totalUser / limit)
    const ticket =await Ticket.aggregate([
      {
        $match: {
          user: new mongoose.Types.ObjectId(req.user._id),
        },
      },
      {
        $lookup: {
          from: "users",
          localField: "user",
          foreignField: "_id",
          as: "userName",
        },
      },
      {
        $project: {
          description: 1,
          "userName.name": 1,
        },
      },
    ])
    const tickets = {
      totalUser,
      pageCount,
      result: ticket,
    }
    if (lastIndex < totalUser) {
      tickets.next = {
        page: page + 1,
      }
    }
    if (startIndex > 0) {
      tickets.prev = {
        page: page - 1,
      }
    }
    console.log(tickets)
    res.status(200).json({ tickets })
  } catch (err) {
    return res.json({ status: false, message: err })
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)