【问题标题】:How to find all docs having array with objects with properties in mongodb?如何在 mongodb 中找到所有具有具有属性的对象的数组的文档?
【发布时间】:2023-03-20 16:07:01
【问题描述】:

我有收藏:

{
 "_id": "1",
 "userId": "2",
 "userName": "A",
}
{
 "_id": "2",
 "userId": "3",
 "userName": "B",
}
{
 "_id": "4",
 "userId": "5",
 "userName": "C",
}
{
 "_id": "6",
 "userId": "7",
 "userName": "D",
}
            

我需要提出某种请求,例如:

db.users.find([
 {
  "userId": "2",
  "userName": "A",
 },
 {
  "userId": "3",
  "userName": "B",
 },
 {
  "userId": "5",
  "userName": "C",
 }])

我想得到:

{
 "_id": "1",
 "userId": "2",
 "userName": "A",
}
{
 "_id": "2",
 "userId": "3",
 "userName": "B",
}
{
 "_id": "4",
 "userId": "5",
 "userName": "C",
}

抱歉,这里的查找请求不那么可读。 Stackoverflow 认为这里的代码太多而文字很少。

【问题讨论】:

    标签: mongodb mongoose nosql


    【解决方案1】:

    你可以试试这样的

    db.collection.find({
      $or: [
        { userId: "2", userName: "A"  },
        { userId: "3", userName: "B" }
      ]
    })
    

    工作Mongo playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-07
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多