【问题标题】:How to show only element of array in output如何在输出中仅显示数组元素
【发布时间】:2021-08-14 19:31:26
【问题描述】:

我有这样的文件。如何在输出中仅显示数组元素。

{
_id: ObjectId("5effaa5662679b5af2c58829"),
 email: “email@example.com”,
 name: {given: “Jesse”, family: “Xiao”},
 age: 31,
 addresses: [{label: “home”,
              street: “101 Elm Street”,
              city: “Springfield”,
              state: “CA”,
              zip: “90000”,
              country: “US”},
             {label: “mom”,
              street: “555 Main Street”,
              city: “Jonestown”,
              province: “Ontario”,
              country: “CA”}]
}

我的查询

{ "$project": { _id : 0, "addresses.country": 1 }  }

想要的输出

"country": “...”

实际输出

{ 
    "addresses" : [
        {
            "country" : "..."
        }
    ]
}

【问题讨论】:

    标签: arrays mongodb project subdocument


    【解决方案1】:

    你可以使用聚合

    • $unwind 解构数组
    • $match 匹配国家
    • $replaceRoot 使其成为根

    这里是代码

    db.collection.aggregate([
      { "$unwind": "$addresses" },
      { "$match": { "addresses.country": "CA" } },
      { "$replaceRoot": { "newRoot": "$addresses" } }
    ])
    

    工作Mongo playground

    【讨论】:

    • 我应该使用 $project.有办法吗? “CA”与任何国家无关。
    • 我可以知道原因“我应该使用项目。”
    【解决方案2】:

    简短的回答是您使用排除。使用 field:0 排除。所以在 find 语句之后你会添加类似:db.project.find({..}, {_id:0:,label:0,city:0..etc})

    【讨论】:

      【解决方案3】:

      解决了

              { "$unwind" : "$addresses" },
              {
                  "$project" : {
                      _id:0.0,
                      "addresses" : "$addresses._id"
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 2021-04-10
        • 2016-12-31
        • 1970-01-01
        • 2020-04-07
        • 1970-01-01
        • 2012-08-04
        • 2021-10-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多