F
F
Fengol2019-03-04 12:46:12
MongoDB
Fengol, 2019-03-04 12:46:12

Is it possible to use logic when querying the database?

Imagine that there is a document containing two fields type (String) and target (Mixed), which, depending on the type, is represented by one of many different objects.

const a = Schema({ a: Number });
const b = Schema({ b: String });

const doc = Schema({ type: String, target: Schema.Types.Mixed });

// если type имеет значение 'a', то поле target является объектом a и т.д.

Is it possible with mongoose to write a query on the data in such a way that the conditions are defined for each specific type? That is, in one query, select data for type `a` in which field 'a' is greater than 5 and less than 10, and for type b, field b must belong to the specified range of characters ['a', 'b', 'c']. If so, please provide a simple example.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
Urukhayy, 2019-03-04
@Fengol

Collection.find({
    $or: [
        {
            "type": "a",
            "target.a": { $gt: 5, $lt: 10 }
        },
        {
            "type": "b",
            "target.b": { $in: ['a', 'b', 'c'] }
        }]
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question