sql >> Databasteknik >  >> NoSQL >> MongoDB

Kombinera två $or-påståenden

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")})

första subquerydb.test.distinct('a', {...});

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

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

varva ner

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

fråga

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 ]

det här borde också fungera (antag att 'inte existerar' och 'null' är samma sak)

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")} }
      ]}
  ]
}
)


  1. MongoDb:hur man skapar rätt (sammansatt) index för data med många sökbara fält

  2. hur räknar man ett $lookup-fält i mongo db?

  3. Sparar numpy array i mongodb

  4. Hur man använder Predis, hur man ställer in (dvs lagrar) en flerdimensionell associativ array?