How to create nested OR/AND query filters in Mongo-Go-Driver?

Susan Sarandon
Release: 2024-11-18 02:16:02
Original
700 people have browsed it

How to create nested OR/AND query filters in Mongo-Go-Driver?

Nested OR/AND Query Filter in Mongo-Go-Driver

When creating complex query filters in MongoDB using the Go driver, it's common to need nested operators like OR and AND. However, the official driver requires the use of bson.D and bson.E elements for building the filter.

To handle nested OR/AND operations, you can combine bson.D and bson.M objects.

Consider the following example where you want to create an AND filter with a nested OR condition:

filter := bson.M{"$and": bson.D{
    {"p", 10},
    {"$or": bson.D{
        {"s", 30},
        {"a", 1}
    }}
}}
Copy after login

This approach will result in the following error: "cannot use primitive.M literal (type primitive.M) as type primitive.E in slice literal."

To resolve this issue, you can define the filter as follows:

filter := bson.D{
    {"p", 10},
    {"$or", bson.A{
        bson.D{{"s", 30}},
        bson.D{{"a", 10}},
    }},
}
Copy after login

Here, instead of using bson.D within bson.D for the nested OR condition, we use bson.A (an array of bson.D elements). This is because $or expects an array of filters.

Another option is to use bson.M for both the main AND filter and the nested OR condition:

filter = bson.M{
    "p": 10,
    "$or": bson.A{
        bson.M{"s": 30},
        bson.M{"a": 10},
    },
}
Copy after login

In this case, you can use bson.M instead of bson.D to define the nested OR condition, as bson.A also allows bson.M elements.

The above is the detailed content of How to create nested OR/AND query filters in Mongo-Go-Driver?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template