簡體   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']
  },
]

我想從mongodb搜索帶有 rep_id 的記錄。 如果 rep_id 不匹配,它應該在 user_ids 數組中搜索相同的 id。 如果它也不存在於 user_ids 數組中,它應該跳過該記錄。 我能夠找到匹配的 rep_id 但如果它不匹配並且它存在於 user_ids 數組中,我該怎么做。 從上面的記錄中,如果 rep_id 是101它應該給我第一條記錄,如果 rep_id 是102它應該給我兩條記錄,因為102存在於兩個 user_ids 數組中。

即使是解決方案的提示就足夠了

使用$or

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

mongoplayground

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM