简体   繁体   English

如何使用节点有条件地从 mongodb 中查找记录

[英]How to conditionally find records from mongodb using node

[ 
  {
   name: 'Some one'
   rep_id: '101',
   user_ids: ['102','103','104']
  },
  {
   name: 'Some one else'
   rep_id: '106',
   user_ids: ['102','103','104','105']
  },
]

I want to search records with rep_id from mongodb .我想从mongodb搜索带有 rep_id 的记录。 If rep_id is not matched it should search the same id in user_ids array.如果 rep_id 不匹配,它应该在 user_ids 数组中搜索相同的 id。 If it's not present in user_ids array as well, it should skip that record.如果它也不存在于 user_ids 数组中,它应该跳过该记录。 I'm able to find with rep_id being matched but how can I do the same if it's not matched and it's present in user_ids array.我能够找到匹配的 rep_id 但如果它不匹配并且它存在于 user_ids 数组中,我该怎么做。 From the above records, if rep_id is 101 it should give me the first record and if rep_id is 102 it should give me the both the records since 102 is present in both user_ids array.从上面的记录中,如果 rep_id 是101它应该给我第一条记录,如果 rep_id 是102它应该给我两条记录,因为102存在于两个 user_ids 数组中。

Even a hint of the solution will be enough即使是解决方案的提示就足够了

use $or使用$or

db.collection.aggregate([
  {
    "$match": {
      "$or": [
        {
          rep_id: "102"
        },
        {
          user_ids: "102"
        }
      ]
    }
  }
])

mongoplayground mongoplayground

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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