简体   繁体   中英

how can find a record in mongodb by null value

there are such documents in a collection:

  {name:'abc', age:'22',job:'writer', place: 'place1',tag:['a','v']},
  {name:'def', age:'24',job:'no job', place: 'place1',tag:['a','f']},
  {name:'ghi', age:'22',job:'writer', place: 'place3',tag:['d','v']},
  {name:'jklm', age:'22',job:'editor', place: 'place4',tag:['a','d']},

i need to search by below condition(user enter details)

searchKey{ 
 sk_age:'22',
 sk_job:['writer','editor']
 sk_place:null,
 sk_tag:null 
}

'place and tag user not entered '
i am writing mongodb quires like below , but this not work, how can find correctly

db.user.find( { 
        age:sk_age,
        job:sk_job,
        place:sk_place,
        tag:sk_tag,
      } ).toArray()

i expect || i need below listed recorders

{name:'abc', age:'22',job:'writer', place: 'place1',tag:['a','v']},
{name:'ghi', age:'22',job:'writer', place: 'place3',tag:['d','v']},
{name:'jklm', age:'22',job:'editor', place: 'place4',tag:['a','d']},

You may use $in operator and also check whether fields are not null something like

const query = {
  age:sk_age,
  job: {'$in': sk_job}
}
if (sk_place !== null) {
  query.place = sk_place;
}
if (sk_tag !== null) {
  query.tag = sk_tag;
}

db.user.find(query).toArray()

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