如何在输出中仅显示数组元素

Posted

技术标签:

【中文标题】如何在输出中仅显示数组元素【英文标题】: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" : "..."
        
    ]

【问题讨论】:

【参考方案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"
            
        

【讨论】:

以上是关于如何在输出中仅显示数组元素的主要内容,如果未能解决你的问题,请参考以下文章