2

MongoDB documents contain an array of objects and what is the best way to query those documents if I want to find and remove an object from an array with some specific value;

Here is an example of the document schema

const mongoose = require("mongoose");

const LibrarySchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
  },
  books: [
    {
      type: new mongoose.Schema({
        bookName: {
          type: String,
          required: true,
        },
        chapterReading: {
          type: Number,
          default: 1,
          required: true,
        },
      }),
    },
  ],
});

const Library = mongoose.model("Library", LibrarySchema);

exports.Library = Library;

If I want to find and remove a book with some bookName

1
  • To remove a specific book identified by its name you use an update operation / method (the U of the CRUD). Further, refer the MongoDB Manual. Commented Sep 29, 2021 at 4:16

1 Answer 1

1

Use $pull

Example :

Library.update({}, { $pull: { books: { bookName: "Yourbookname" } } })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.