简体   繁体   中英

Complex statement in MongoDB AND & OR conditions

Continuing on my project, I need to translate some SQL statements to mongoDB

My SQL Statement is:

Delete from 'table' where proc_id = $xxx and (day_id < $day OR day_id > $anotherDay)

Now my condition array is this:

$condicion = array(
            'proc_id' => $xxx,
            '$or' => array(
                'day_id' => array(
                    '$lt' => $day,
                    '$gt' => $anotherDay

                    )
                )
            );

The function made for delete in mongo collections returns cannot delete...

Some help please?

Each "day_id" would be in it's own $or argument:

$query = array(
    'proc_id' = > $xxx,
    '$or' => array(
        array( 'day_id' => array ( '$lt' => $day ) ),
        array( 'day_id' => array ( '$gt' => $anotherDay ) ),
    )
)

That is how $or conditions work as a "list" of possible expressions.

The JSON syntax is clearer to visualise:

{
    "proc_id": $xxx,
    "$or": [
        { "day_id": { "$lt": $day } },
        { "day_id": { "$gt": $anotherDay }}
    ]
}

Since there is a very clear distinction between a "list" and an "object" definition. $or conditions are "lists" of "objects", and that means you list the full condition just as if it were a query in itself. Since this is not called within an $elemMatch .

And of course the "DELETE" part is the .remove() method:

$collection->remove($query)

There are general examples and resources in the core documentation SQL to MongoDB Mapping Chart , where if the examples there do not immediately help, the linked articles and presentations should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM