【问题标题】:mongoose return an object from an array based on condition猫鼬根据条件从数组中返回一个对象
【发布时间】:2021-09-02 19:04:42
【问题描述】:

我想从 MongoDB 记录中的数组中获取特定对象。我想获取整个集合,因此我无法在 find 中应用我的条件,但在记录中,我有一个数组,我想根据条件从该数组中返回一个对象。

 await model
  .find({})
  .select("translations")
  .then((data: any) => {
    return res.status(200).json({
      data
    });
  });

现在这里的翻译有很多对象

[
 {id:'', name: 'EN'},
 {id:'', name: 'AR'}, 
 {id:'', name: 'FR'}
]

我怎样才能只返回名称为“EN”的翻译

【问题讨论】:

    标签: node.js database mongodb express nosql


    【解决方案1】:
    db.collection.aggregate(
    [
      {
        '$project': {
          'translation': {
            '$filter': {
              'input': '$translation', 
              'as': 't', 
              'cond': {
                '$eq': [
                  '$$t.name', 'EN'
                ]
              }
            }
          }
        }
      }
    ]   
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多