【问题标题】:How to use $elemMatch and $expr MongoDB?如何使用 $elemMatch 和 $expr MongoDB?
【发布时间】:2020-12-02 01:26:31
【问题描述】:

我有一个收藏:

 {
_id: ObjectId('5fb25b089b86a21e3fe00dc8'),
sellingPoint: [
  {
    organizationUnitId: ObjectId('5fb34ba2d5f7ad3cee5b5f6b'),
    name: 'HP',
    amount: 100,
    miximumSell: 0,
  },
  {
    organizationUnitId: ObjectId('5fb34ba2d5f7ad3cee5b5f7b'),
    name: 'HD',
    amount: 100,
    miximumSell: 200,
  },
],
},
{
_id: ObjectId('5fb25b089b86a21e3fe00dc9'),
sellingPoint: [
  {
    organizationUnitId: ObjectId('5fb34ba2d5f7ad3cee5b5f6b'),
    name: 'HP',
    amount: 100,
    miximumSell: 0,
  },
  {
    organizationUnitId: ObjectId('5fb34ba2d5f7ad3cee5b5f7b'),
    name: 'HD',
    amount: 100,
    miximumSell: 99,
  },
  ],
},
{
_id: ObjectId('5fb25b089b86a21e3fe00dc9'),
sellingPoint: [
  {
    organizationUnitId: ObjectId('5fb34ba2d5f7ad3cee5b5f6b'),
    name: 'HP',
    amount: 100,
    miximumSell: 0,
  },
  {
    organizationUnitId: ObjectId('5fb34ba2d5f7ad3cee5b5f7b'),
    name: 'HD',
    amount: 100,
    miximumSell: 150,
  },
},

我正在尝试让文档有 organizationUnitId: ObjectId('5fb34ba2d5f7ad3cee5b5f7b') && miximumSeel > amount.

我尝试这样做但失败了:

    db.users.aggregate([
  {
    'sellingPoint':{
      $elemMatch: {
        $and:[
            { 'organizationUnitId': ObjectId('5fb34ba2d5f7ad3cee5b5f7b')},
            {$expr : 
              { $lt: ['$amount', '$miximumSell'] }
             }
        ]
      }
    }
  }
])

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    你可以试试,

    • $filter 根据您的条件从 sellingPoint 数组中获取匹配的文档
    • $match 过滤非空结果
    db.collection.aggregate([
      {
        $addFields: {
          sellingPoint: {
            $filter: {
              input: "$sellingPoint",
              cond: {
                $and: [
                  { $eq: ["$$this.organizationUnitId", ObjectId("5fb34ba2d5f7ad3cee5b5f7b")] },
                  { $lt: ["$$this.amount", "$$this.miximumSell"] }
                ]
              }
            }
          }
        }
      },
      { $match: { sellingPoint: { $ne: [] } } }
    ])
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 2016-02-20
      相关资源
      最近更新 更多