我在db中有员工json如下,我想创建" addressId"(键)和" city"(值)的地图并返回结果。
{
"_id" :1,
"_class" : "com.entity.Employee",
"clientId" : 1,
"addresses" : [
{
"addressId" : 1,
"street" : "ghi",
"city" : "Hyderabad"
},
{
"addressId" : 2,
"street" : "abc",
"city" : "Bangalore"
},
{
"addressId" : 3,
"street" : "def",
"city" : "Chennai"
}
]
}
请建议我可以使用哪个操作员以及是否可以使用$ project实现。
答案 0 :(得分:1)
是的,您必须使用带有展开的投影和forEach来创建键值对
尝试以下mongo查询
db.collection_name.aggregate([{"$unwind":"$addresses"},{"$project": {"addressId": "$addresses.addressId", "city":"$addresses.city", "_class":"$_class","clientId":"$clientId"} }]).forEach(function(ojb){ojb[ojb.addressId]=ojb.city; printjson(ojb);});