userMod2
userMod2

Reputation: 8960

MongoDB - Can i use $and and $or in one match?

Just getting started with MongoDB - is it possible to have a $or and $and in one statement.

So atm, I have the following search statement:

find(
{$or: [{tags : {$in: ["test", "output"]}}, {$text:{$search: "test" }} ]},
{_id:0, publicID: 1, story:1}
)

However I want to check 2 fields verified and flagged equal false.

So i see I can't do:

find(
{$or: [{tags : {$in: ["test", "output"]}}, {$text:{$search: "test" }} ]},
{$and: [{verified : false}, {$flagged : false } ] },
{_id:0, publicID: 1, story:1}
)

which leads me to think i need to use aggregate but not sure how to do a $or and $and in one statement.

Any help appreciated.

Thanks.

Upvotes: 0

Views: 108

Answers (1)

CodeMan
CodeMan

Reputation: 1405

I believe this has been answered before, but you can combine logical query operators in MongoDB including $and and $or.

In your example you could do:

find({
    $and : [
        { $or : [
            { tags : { $in: ["test", "output"] } },
            { $text : { $search : "test" } }
        ]},
        { verified : false },
        { flagged : false }
    ]},
    { _id:0, publicID : 1, story : 1 }
);

Upvotes: 3

Related Questions