0

I'm a little unclear about indexing in mongodb.

Below I have a schema (in mongoose) for a book entry. It has an owner and a requestee.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const bookSchema = Schema({
    owner    : { type: Schema.Types.ObjectId, ref: 'User', index: true },
    title    : String,
    author   : String,
    image    : String,
    added    : Date,
    requestee: { type: Schema.Types.ObjectId, ref: 'User', index: true },
}, {collection: 'books'})

module.exports = mongoose.model("Book", bookSchema);

What I want to do is to be able to query from both perspectives.

For the owner of the book:

Book.find({owner: ObjectId(user._id)})

This will be able to tell me if anyone is requesting the book

For the requestee:

Book.find({requestee: ObjectId(requestee._id)})

This will be able to tell me the requests a requestee has made.

I'm unclear about if what I have above is correct in terms of indexes. Can I have multiple single key indexes, or is what I'm doing scanning every document looking for a match?

Running the queries from the shell seem to work but again don't know if this is correct.

2
  • Here is little bit more about indexes and indexes strategies. If you are looking ways to verify if the indexes are utilized, you can use docs.mongodb.com/manual/tutorial/measure-index-use Commented Feb 10, 2017 at 20:07
  • @Veeram thanks for the measure index use doc, I think my assumption is correct based off what I'm seeing in the explain("executionStats"). I think what you have is a perfectly acceptable answer. If you want to put it as an answer I'll accept it. Commented Feb 10, 2017 at 20:33

1 Answer 1

2

You can run explain on the query to view the index usage. Take a look at compound index as well if that is better for your use case.

More information here - https://docs.mongodb.com/manual/tutorial/measure-index-use/

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.