Home > Software engineering >  MongoDB how to find all documents who's array contains a specific string?
MongoDB how to find all documents who's array contains a specific string?

Time:03-29

Below is an example of my "Event" document in MongoDB. I want to be able to query all of the Event documents where the attendees array contains "623d03730e82c57fefa52fb2" (a user ID).

Here is one of my event documents:

_id: ObjectId(623ce74372a28f08dea6c959)
description: "Fun BBQ to celebrate my 21st!"
host: "623d03730e82c57fefa52fb2"
invitees: Array
location: "My address..."
name: "Fun Birthday BBQ"
private: true
date: "03/28/22"
end: "11:15 PM"
start: "06:35 PM"
attendees:Array
   0: "623d03730e82c57fefa52fb2"

Here is my broken query code:

    String id = "623d03730e82c57fefa52fb2";
    // I have also tried Document queryFilter = new Document("attendees", id);
    Document queryFilter = new Document("attendees", new Document("$in", Arrays.asList(id)));

The above code always returns an empty result. To clarify I am using Java and MongoDB Realms but that shouldn't matter.

CodePudding user response:

You don't need $in, use only $eq is ok.

db.collection.find({
  attendees: "623d03730e82c57fefa52fb2"
})

mongoplayground

CodePudding user response:

For easier and more efficient queries, it's important that the types of field values remain consistent.

For example, if "_id" is stored at an ObjectId, then query parameters should also be of type ObjectId. Likewise, if they are strings, then consistently use strings.

If different value types are stored for individual field values, successful queries can still be possible, but not as efficiently since the field types must be considered in the queries. For example, if trying to find a doc by a field that may have a string or an ObjectId type, the query must either search for both types, or the query writer must know the type beforehand. It's easier and more efficient to just pick one type for a field and stick to it.

  • Related