【问题标题】:MongoDB query to Retrieve all the rows which contain a particular element inside an arrayMongoDB查询以检索包含数组中特定元素的所有行
【发布时间】:2020-03-25 01:45:29
【问题描述】:

我是使用 MongoDb 的新手,我被困在这个查询中, 我想检索所有可用的小尺寸行

{
  "_id":ObjectId("562e7c594c12942f08fe4192"),
  "sizes":["small","medium","large"]
},
{
  "_id":ObjectId("562e7c594c22942f08fe4193"),
  "sizes":["small"]
},
{
  "_id":ObjectId("562e7c594c12942f08fe4199"),
  "sizes":["medium","large"]
},

我想要所有小尺寸的行,即

{
  "_id":ObjectId("562e7c594c12942f08fe4192"),
  "sizes":["small","medium","large"]
},
{
  "_id":ObjectId("562e7c594c22942f08fe4193"),
  "sizes":["small"]
},

【问题讨论】:

    标签: mongodb mongoose mongodb-atlas


    【解决方案1】:

    你需要使用$elemMatch

    xxx.find(
       { sizes: { $elemMatch: { $eq:"small" } } }
    )
    

    https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

    【讨论】:

      【解决方案2】:

      我不知道你已经尝试过哪些命令,但是,也许可以尝试使用这个命令:

      myCursor = db.inventory.find( { 'sizes': "small" } )
      

      由于这只会显示前 20 个文档,因此您可以放置​​一个循环:

      while (myCursor.hasNext()) {
          print(tojson(myCursor.next()));
      }
      

      参考:https://docs.mongodb.com/guides/server/read_queries/

      【讨论】:

        【解决方案3】:

        试试这个

        db.sales.aggregate([
         {
            $project: {
                 items: {
                    $filter: {
                        input: "$items",
                        as: "item",
                        cond: { $gte: [ "$$item.sizes", small] }
                    }
                  }
              }
           }
        }
        ])
        

        db.users.find({sizes': "small"});
        

        【讨论】:

          猜你喜欢
          • 2020-03-14
          • 1970-01-01
          • 2017-02-15
          • 2017-11-24
          • 1970-01-01
          • 1970-01-01
          • 2021-06-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多