Improving Performance of MongoDB Query for Counting Contacts in a Group

I’m encountering performance issues with a MongoDB query used to count contacts belonging to specific contact groups. Initially, this approach worked well with a small dataset, but as the number of contacts in the collection has scaled to over 800k documents, the query’s execution time has become prohibitively slow (approximately 16-25 seconds).

Database Schema:

Schema for Contact:

const Contact = new mongoose.Schema(
  {
    name: String,
    email: { type: String, required: true },
    user: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
    groups: [{ type: mongoose.Schema.Types.ObjectId, ref: "ContactGroup" }]
  },
  { timestamps: true }
);

Schema for ContactGroup:

const ContactGroup = new mongoose.Schema(
  {
    title: { type: String, required: true },
    description: { type: String, default: "" },
    user: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
  },
  { timestamps: true }
);

The query I’m running:

const countdocs = async (query) => {
  return Contact.countDocuments(query);
};

const dt = await countdocs({
  $expr: {
    $in: [mongoose.Types.ObjectId(group._id), "$groups"]
  }
});

I’ve attempted to create an index on the groups field in the Contact collection, but the query’s performance remains suboptimal. Could anyone suggest alternative approaches or optimizations to improve the query’s execution time? Additionally, I’m open to feedback on the current data modeling and indexing strategies.

Any assistance or insights would be greatly appreciated. Thank you!

Can you run the query from a shell or compass with explain to show the execution plan that’s being used?
What index did you create and can you show an example document from your collection?