DEV Community

avinash-repo
avinash-repo

Posted on

MongoDB Quries

The provided script demonstrates several MongoDB operations, including data insertion, updates, deletions, aggregation, and queries. I will provide an overview of each operation with example data and expected output.

  1. Data Insertion:
   db.students.insertMany([
     { id: 1, name: 'Ryan', gender: 'M' },
     { id: 2, name: 'Joanna', gender: 'F' },
     { id: 3, name: 'Rahul', gender: 'M' }
   ]);
Enter fullscreen mode Exit fullscreen mode
  1. Profiling and Query Execution:
   db.setProfilingLevel(1, { slowms: 100 });
   db.system.profile

- 
.find().pretty();
Enter fullscreen mode Exit fullscreen mode
  1. Inserting and Updating Email:
   db.students.insert({ id: 3, name: 'Rahul', gender: 'M' });
   db.students.update({ id: 1 }, { $set: { email: 'ak@gm.com' } });
   db.students.update({ id: 2 }, { $set: { email: 'ak2@gm.com' } });
   db.students.update({ id: 3 }, { $set: { email: 'ak3@gm.com' } });
Enter fullscreen mode Exit fullscreen mode
  1. Upsert and Deletion:
   db.students.update({ id: 11 }, { $set: { name: 'Sangita', gender: 'F' } }, { upsert: true });
   db.students.deleteOne({ id: 2 });
Enter fullscreen mode Exit fullscreen mode
  1. Inserting and Updating Marks:
   db.marks.insertMany([
     { sid: 1, pass: 'Failed', marks: 32, ncc: 'Y' },
     { sid: 2, pass: 'Passed', marks: 40, ncc: 'N' },
     { sid: 3, pass: 'Passed', marks: 70, ncc: 'Y' }
   ]);

   db.marks.updateMany({ ncc: 'Y' }, { $set: { award: 'yyes' } });
Enter fullscreen mode Exit fullscreen mode
  1. Aggregation - Joining Students and Marks:
   db.students.aggregate([
     {
       $lookup: { from: 'marks', localField: 'id', foreignField: 'sid', as: 'SMarks' }
     },
     { $project: { _id: 0, SMarks: { _id: 0 } } }
   ]);
Enter fullscreen mode Exit fullscreen mode
  1. Aggregation - Calculating Total Marks:
   db.marks.aggregate([
     { $group: { _id: null, Tsum: { $sum: '$marks' } } },
     { $project: { _id: 0, Tsum: 1 } }
   ]);

   db.marks.aggregate([
     { $group: { _id: null, Tavg: { $avg: '$marks' } } }
   ]);
Enter fullscreen mode Exit fullscreen mode
  1. Aggregation - Additional Statistics and Reshaping:
   db.marks.aggregate([
     {
       $group: {
         _id: null,
         Tmax: { $max: '$marks' },
         Tmin: { $min: '$marks' },
         TTsum: { $sum: '$marks' },
         TTavg: { $avg: '$marks' },
         Tcount: { $sum: 1 }
       }
     },
     {
       $addFields: { empInfo: { $ifNull: ['$empInfo', [{ msg: 'deleted by deletedOne' }]] } }
     },
     { $project: { _id: 0 } }
   ]);
Enter fullscreen mode Exit fullscreen mode
  1. Replacing Document in Students Collection:
   db.students.replaceOne(
     { email: 'ak3@gm.com' },
     {
       name: 'John Doe',
       age: 26,
       email: 'ak3@gm.com',
       address: { city: 'New York', country: 'USA' }
     }
   );
Enter fullscreen mode Exit fullscreen mode
  1. Example Queries:
    Uncommented queries for reference:

    • db.students.find()
    • db.marks.find({ ncc: 'Y' })
    • db.marks.find({ marks: { $gte: 40 } })
    • db.marks.aggregate([{$match:{ncc:{$in:["Y"]}}}])
    • db.marks.aggregate([{$match:{ncc:"N"}}])
  2. Inserting Data into "mytags" Collection:

    db.mytags.insertMany([
      // Example data provided
    ]);
    
  3. Various Aggregation and Query Operations on "mytags":

    • Please refer to the comments and uncommented queries in the script for details.

Note: The actual output of queries may vary based on the specific data present in the database at the time of execution.

The provided script involves the insertion of data into the "mytags" collection and subsequent MongoDB queries and aggregations. I will provide an overview of each operation with example data and expected output.

  1. Inserting Data into "mytags" Collection:

    db.mytags.insertMany([
      {
        "id": 1,
        "title": "Introduction to MongoDB",
        "tags": ["mongodb", "database"],
        "status": "active",
        "like": 50
      },
      {
        "id": 2,
        "title": "Exploring NoSQL Concepts",
        "tags": ["nosql", "database"],
        "status": "inactive",
        "like": 250
      },
      {
        "id": 3,
        "title": "Building Scalable Applications",
        "tags": ["php", "nosql", "scalability"],
        "status": "inactive",
        "like": 1050
      },
      {
        "id": 4,
        "title": "Data Modeling in MongoDB",
        "tags": ["mongodb", "database", "modeling"],
        "status": "active",
        "like": 350
      },
      {
        "id": 5,
        "title": "Node with MongoDB",
        "tags": ["nodejs", "sql", "react"],
        "status": "active",
        "like": "na"
      }
    ]);
    
  2. Queries and Aggregations on "mytags":

    • Uncommented queries for reference:
      • db.mytags.find({like:{$gt:500},status:{$eq:"active"}})
      • db.mytags.find({status:"inactive"})
      • db.mytags.find({ status: { $eq: "active" } })
      • db.mytags.aggregate([{$match:{status:"active",like:{$gt:51}}}]
      • db.mytags.find({ title: { $regex: /^Building/ } })
      • db.mytags.find({$or:[{status:"active",tags:{$in:["mongodb"]}}, {like:{$gt:1000}}]})
      • db.mytags.find({$and:[{status:"inactive"}, {like:{$lt:251}}]})
      • db.mytags.find().sort({ like: -1 })
      • db.mytags.aggregate([{ $unwind: "$status" }])
      • db.mytags.aggregate([{ $match: { like: { $gt: 50 } } }])
      • db.mytags.aggregate([{ $skip: 2 },{ $limit: 3 }])
      • db.mytags.aggregate([{ $facet: { averageLike: [{ $group: { _id: null, avgLike: { $avg: "$like" } } }], totalLike: [{ $group: { _id: null, totalQty: { $sum: "$like" } } }] } }])
      • db.mytags.countDocuments({ like: { $gt: 50 } })
      • db.mytags.distinct("status")
      • db.mytags.distinct("tags")
      • db.mytags.find({ like: { $type: "string" } })
      • db.mytags.find({tags:{$in:["mongodb","database"]}})
      • db.mytags.find({tags: { $all: ["mongodb", "database"] } })

Note: The actual output of queries may vary based on the specific data present in the "mytags" collection at the time of execution. Ensure the data aligns with the examples provided for accurate results.

Certainly, let's provide the expected output for each query based on the example data you provided earlier.

  1. Query: db.mytags.find({like:{$gt:500},status:{$eq:"active"}})

    • Expected Output: Documents where 'like' is greater than 500 and 'status' is "active".
  2. Query: db.mytags.find({status:"inactive"})

    • Expected Output: Documents where 'status' is "inactive".
  3. Query: db.mytags.find({ status: { $eq: "active" } })

    • Expected Output: Documents where 'status' is "active".
  4. Query: db.mytags.aggregate([{$match:{status:"active",like:{$gt:51}}}])

    • Expected Output: Aggregated documents where 'status' is "active" and 'like' is greater than 51.
  5. Query: db.mytags.find({ title: { $regex: /^Building/ } })

    • Expected Output: Documents where 'title' starts with "Building".
  6. Query: db.mytags.find({$or:[{status:"active",tags:{$in:["mongodb"]}}, {like:{$gt:1000}}]})

    • Expected Output: Documents where 'status' is "active" and includes the tag "mongodb", or 'like' is greater than 1000.
  7. Query: db.mytags.find({$and:[{status:"inactive"}, {like:{$lt:251}}]})

    • Expected Output: Documents where 'status' is "inactive" and 'like' is less than 251.
  8. Query: db.mytags.find().sort({ like: -1 })

    • Expected Output: All documents sorted in descending order based on the 'like' field.
  9. Query: db.mytags.aggregate([{ $unwind: "$status" }])

    • Expected Output: Unwound documents based on the 'status' field.
  10. Query: db.mytags.aggregate([{ $match: { like: { $gt: 50 } } }])

    • Expected Output: Aggregated documents where 'like' is greater than 50.
  11. Query: db.mytags.aggregate([{ $skip: 2 },{ $limit: 3 }])

    • Expected Output: Skipped the first 2 documents and limited the result to 3 documents.
  12. Query: db.mytags.aggregate([{ $facet: { averageLike: [{ $group: { _id: null, avgLike: { $avg: "$like" } } }], totalLike: [{ $group: { _id: null, totalQty: { $sum: "$like" } } }] } }])

    • Expected Output: Aggregated result providing average and total of the 'like' field.
  13. Query: db.mytags.countDocuments({ like: { $gt: 50 } })

    • Expected Output: Count of documents where 'like' is greater than 50.
  14. Query: db.mytags.distinct("status")

    • Expected Output: Distinct values of the 'status' field.
  15. Query: db.mytags.distinct("tags")

    • Expected Output: Distinct values of the 'tags' field.
  16. Query: db.mytags.find({ like: { $type: "string" } })

    • Expected Output: Documents where the 'like' field is of type string.
  17. Query: db.mytags.find({tags:{$in:["mongodb","database"]}})

    • Expected Output: Documents where 'tags' includes "mongodb" or "database".
  18. Query: db.mytags.find({tags: { $all: ["mongodb", "database"] } })

    • Expected Output: Documents where 'tags' includes both "mongodb" and "database".

Please note that the actual output may vary based on the data in your MongoDB collection at the time of execution.

Top comments (0)