mongodb 查询使用 $gte 和 $lte 运算符过滤对象数组

mongodb query to filter the array of objects using $gte and $lte operator

我的文件:

[{
  "_id":"621c6e805961def3332bcf97",
  "title":"monk plus",
  "brand":"venture electronics",
  "category":"earphones",
  "variant":[
      {
         "price":1100,
         "impedance":"16ohm"
      }, 
      {
        "price":1600,
        "impedance":"64ohm"
      }],
 "salesCount":185,
 "buysCount":182,
 "viewsCount":250
},
{
 "_id":"621c6dab5961def3332bcf92",
 "title":"nokia1",
 "brand":"nokia",
 "category":"mobile phones",
 "variant":[
      {
        "price":10000,
        "RAM":"4GB",
        "ROM":"32GB"
      },
      {
        "price":15000,
        "RAM":"6GB",
        "ROM":"64GB"
       }, 
      {
        "price":20000,
        "RAM":"8GB",
        "ROM":"128GB"
    }],
   "salesCount":34,
   "buysCount":21,
   "viewsCount":80
}]

预期输出

 [{
    _id:621c6e805961def3332bcf97
    title:"monk plus"
    brand:"venture electronics"
    category:"earphones"
    salesCount:185
    viewsCount:250
    variant:[
              {
                price:1100
                impedance:"16ohm"
               }]
}]

我试过这种聚合方式

[{
  $match: {
     'variant.price': {
      $gte: 0,$lte: 1100
      }
   }}, 
{
  $project: {
        title: 1,
        brand: 1,
        category: 1,
        salesCount: 1,
        viewsCount: 1,
   variant: {
         $filter: {
             input: '$variant',
             as: 'variant',
             cond: {
                 $and: [
                    {
                      $gte: ['$$variant.price',0]
                    },
                    {
                      $lte: ['$$variant.price',1100]
                    }
                   ]
                }
              }
            }
         }}]

此方法 return 是预期的输出,现在我的问题是还有其他更好的方法可以 return 预期的 output.Moreover 在此先感谢您,因为我是新手nosql 数据库所以我很想从 community.Take 中学习关于预期输出的注释特定文档的所有属性必须 return 只有我想根据价格过滤的对象的变体数组。

您的解决方案很好,只需确保在应用此步骤之前应用您的 $match 和分页以加快查询速度

你的聚合管道没有问题,还有其他方法可以做到。如果您只想 return 匹配文档, 只匹配第一个数组元素 ,这里有另一种方法。 (不幸的是,.$ 语法仅 return 是第一个匹配项。)

db.collection.find({
  // matching conditions
  "variant.price": {
    "$gte": 0,
    "$lte": 1100
  }
},
{
  title: 1,
  brand: 1,
  category: 1,
  salesCount: 1,
  viewsCount: 1,
  // only return first array element that matched
  "variant.$": 1
})

mongoplayground.net 上试用。

或者,如果您想使用聚合管道和 return 除了过滤后的数组之外的所有匹配文档,您可以使用 [=13= 使用您想要的元素“覆盖”数组](或其别名 "$addFields")。这样做意味着您不需要 "$project" 任何东西。

db.collection.aggregate([
  {
    "$match": {
      "variant.price": {
        "$gte": 0,
        "$lte": 1100
      }
    }
  },
  {
    "$set": {
      "variant": {
        "$filter": {
          "input": "$variant",
          "as": "variant",
          "cond": {
            "$and": [
              { "$gte": [ "$$variant.price", 0 ] },
              { "$lte": [ "$$variant.price", 1100 ] }
            ]
          }
        }
      }
    }
  }
])

mongoplayground.net 上试用。