MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Combina due affermazioni $or

use test
db.test.insert({a:1})
db.test.insert({a:2, Date2:new Date("01/07/2012")})
db.test.insert({a:3, Date2:new Date("01/08/2012")})
db.test.insert({a:4, Date1:new Date("01/07/2012"), Date2:new Date("01/07/2012")})
db.test.insert({a:5, Date1:new Date("01/07/2012")})
db.test.insert({a:6, Date1:new Date("01/08/2012")})

primo subquerydb.test.distinct('a', {...});

secondo subquerydb.test.distinct('a', {...});

(Date1 == null || Date1 <= today) && (Date2 == null || Date2 <= today)

rilassati

Date1 == null && Date2 == null ||
Date1 == null && Date2 <= today ||
Date1 <= today && Date2 == null ||
Date1 <= today && Date2 <= today ||

interrogare

db.test.find(
{
  $or : 
  [
    {$and: [
        {"Date1": {"$exists": false}},
        {"Date2": {"$exists": false}}
      ]},
    {$and: [
        {"Date1": {"$exists": false}},
        {"Date2": {
            "$exists": true,
            "$lte": new Date("2012-01-07T04:45:52.057Z")}
        }
      ]},
    {$and: [
        {"Date2": {"$exists": false}},
        {"Date1": {
            "$exists": true,
            "$lte": new Date("2012-01-07T04:45:52.057Z")}
        }
      ]},
    {$and: [
        {"Date2": {
            "$exists": true,
            "$lte": new Date("2012-01-07T04:45:52.057Z")}
        },
        {"Date1": {
            "$exists": true,
            "$lte": new Date("2012-01-07T04:45:52.057Z")}
        }
      ]}
  ]
})
>[ 1 ]

dovrebbe funzionare anche questo (supponiamo che 'non esiste' e 'null' siano gli stessi)

db.test.find(
{
  $and : 
  [
    {$or: [
        {"Date1": null},
        {"Date1": { "$lte": new Date("2012-01-07T04:45:52.057Z")} }
      ]},
    {$or: [
        {"Date2": null},
        {"Date2": { "$lte": new Date("2012-01-07T04:45:52.057Z")} }
      ]}
  ]
}
)