[英]MongoDB how to find all documents who's array contains a specific string?
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).下面是我在 MongoDB 中的“事件”文档的示例。我希望能够查询与会者数组包含“623d03730e82c57fefa52fb2”(用户 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.澄清一下,我使用的是 Java 和 MongoDB 领域,但这无关紧要。
You don't need $in
, use only $eq
is ok.你不需要$in
,只使用$eq
就可以了。
db.collection.find({
attendees: "623d03730e82c57fefa52fb2"
})
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
.例如,如果"_id"
存储在ObjectId
中,则查询参数也应为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.例如,如果尝试通过可能具有字符串或ObjectId
类型的字段find
文档,则查询必须搜索这两种类型,或者查询编写者必须事先知道类型。 It's easier and more efficient to just pick one type for a field and stick to it.只为一个字段选择一种类型并坚持下去会更容易、更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.