【问题标题】:How to query by one field and get specific field in mongoose?如何按一个字段查询并获取猫鼬中的特定字段?
【发布时间】:2017-09-30 18:40:44
【问题描述】:

我有一个集合如下,

我想获取特定国家/地区的城市。查询应该是什么?

这是我尝试过的。

db.getCollection('_event').find([
 {$match: {}},
 {$project: {
  cities: {
   $filter: {
    input: 'city',
    as: 'r',
    cond: {$eq: ['$$r.country', 'Portugal']}
   }
  }
 }}
])

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

请按如下方式使用

db.getCollection('_event').find(
    {'location.country':'Portugal'},{'location.city':1}
    )

【讨论】:

    【解决方案2】:

    您尝试的方式是使用 Aggregation 实现的 Pipeline 方式(用于修改使用聚合)

    db.getCollection('_event').aggregation([
     {$match: {}},
     {$project: {
      cities: {
       $filter: {
        input: 'city',
        as: 'r',
        cond: {$eq: ['$$r.country', 'Portugal']}
       }
      }
     }}
    ])
    

    或以简单的方式(获取整个模型):-

     1   db.getCollection('_event').find({"location.country":"Portugal"})
     2   db.getCollection('_event').find({"location.country":\Portugal\}) 
    

    第二个和葡萄牙一样

    谢谢。

    【讨论】:

      猜你喜欢
      • 2016-10-13
      • 2016-02-17
      • 1970-01-01
      • 2020-08-07
      • 2016-09-01
      • 2020-07-25
      • 1970-01-01
      • 2019-05-04
      • 2019-12-12
      相关资源
      最近更新 更多