mongoDb条件投影查询

问题描述 投票:0回答:1

我有一些数据如下:

{MS: 'MS1', fileName: 'file1', RSCP: 75, EcNo: 10, ...}
{MS: 'MS2', fileName: 'file1', RSCP: 76, EcNo: 11, ...}
{MS: 'MS3', fileName: 'file1', RSCP: 77, EcNo: 12, ...}
{MS: 'MS4', fileName: 'file1', RSCP: 78, EcNo: 13, ...}

我需要这样查询数据:

find all documents that fileName = file1
if MS = MS1 return RSCP
if MS = MS2 return EcNo

如何在一次查询中像这样查询mongo?

mongodb conditional-statements projection
1个回答
0
投票

您可以在下面的汇总查询中尝试:

db.collection.aggregate([
  /** filter docs with condition */
  {
    $match: {
      fileName: "file1"
    }
  },
  /** Re-create `EcNo` & `RSCP` fields based on conditions 
   * `$$REMOVE` completely removes the field
   */
  {
    $addFields: {
      EcNo: { $cond: [ { $eq: [ "$MS", "MS1" ] }, "$$REMOVE", "$EcNo" ] },
      RSCP: { $cond: [ { $eq: [ "$MS", "MS2" ] }, "$$REMOVE", "$RSCP" ] }
    }
  }
])

测试: mongoplayground

© www.soinside.com 2019 - 2024. All rights reserved.