我有这样的文档结构:
{
favourite_shops: [
{
shop_id: "5961352278cba91cc6a6e8cc",
time: "2017-07-11T14:43:35.465Z"
},
{
shop_id: "5964e446c15c760f9b646d99",
time: "2017-07-11T14:44:40.429Z"
},
{
shop_id: "5964e446c15c760f9b646d98",
time: "2017-07-11T14:44:50.988Z"
}
]
}
我怎样才能将其转换为这样的东西:
{
favourite_shops: [
"5961352278cba91cc6a6e8cc",
"5964e446c15c760f9b646d99",
"5964e446c15c760f9b646d98"
]
}
您可以$map
数组本身并仅获取所需的字段。(这是在查询本身内完成的,而不是在您收到文档后完成的(
例。
给定文件;
> db.Shopping.find().pretty()
{
"_id" : ObjectId("59651ce38828356e1a39fde9"),
"favourite_shops" : [
{
"shop_id" : "5961352278cba91cc6a6e8cc",
"time" : "2017-07-11T14:43:35.465Z"
},
{
"shop_id" : "5964e446c15c760f9b646d99",
"time" : "2017-07-11T14:44:40.429Z"
},
{
"shop_id" : "5964e446c15c760f9b646d98",
"time" : "2017-07-11T14:44:50.988Z"
}
]
}
{
"_id" : ObjectId("59665cf3d8145b41e5d2f5da"),
"favourite_shops" : [
{
"shop_id" : "2222",
"time" : "2017-07-11T14:43:35.465Z"
},
{
"shop_id" : "4444",
"time" : "2017-07-11T14:44:40.429Z"
},
{
"shop_id" : "6666",
"time" : "2017-07-11T14:44:50.988Z"
}
]
}
$map
favourite_shops
数组({$match}
块是可选的,如果您想要所有文档的购物ID,则可以删除(
> db.Shopping.aggregate([[
{
"$match": {
"_id": ObjectId("59651ce38828356e1a39fde9")
}
},
{
"$project": {
"my_favourite_shops": {
"$map": {
"input": "$favourite_shops",
"as": "each_shop",
"in": "$$each_shop.shop_id"
}
}
}
}
]).pretty()
{
"_id" : ObjectId("59651ce38828356e1a39fde9"),
"my_favourite_shops" : [
"5961352278cba91cc6a6e8cc",
"5964e446c15c760f9b646d99",
"5964e446c15c760f9b646d98"
]
}
而且,使用 mongodb 3.4.4,我简直可以在嵌套字段上$project
,
db.Shopping.aggregate([{"$project": {"my_favourite_shops": "$favourite_shops.shop_id"}}]).pretty()
{
"_id" : ObjectId("59651ce38828356e1a39fde9"),
"my_favourite_shops" : [
"5961352278cba91cc6a6e8cc",
"5964e446c15c760f9b646d99",
"5964e446c15c760f9b646d98"
]
}
{
"_id" : ObjectId("59665cf3d8145b41e5d2f5da"),
"my_favourite_shops" : [
"2222",
"4444",
"6666"
]
}
假设我们有这样的数据结构:
const data = {
favourite_shops: [
{
shop_id: "5961352278cba91cc6a6e8cc",
time: "2017-07-11T14:43:35.465Z"
},
{
shop_id: "5964e446c15c760f9b646d99",
time: "2017-07-11T14:44:40.429Z"
},
{
shop_id: "5964e446c15c760f9b646d98",
time: "2017-07-11T14:44:50.988Z"
}
]
};
只是一点ES6的魔力:
const result = {
favourite_shops: []
};
data.favourite_shops.forEach(el => result.favourite_shops.push(el.shop_id));
第二种优雅的方法:
const result = {
favourite_shops: data.favourite_shops.map(el => el.shop_id)
};