我有这样的文件结构:
{
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"
]
}
答案 0 :(得分:1)
假设我们有这样的数据结构:
icon_img = cv2.imread("icon.png")
icon_img1= cv2.resize(icon_img, (20,20))
x_offset=y_offset=5
img[y_offset:y_offset+icon_img1.shape[0], x_offset:x_offset+icon_img1.shape[1]] = icon_img1
cv2.putText(img, "my_text", (x_offset+icon_img1.shape[1], y_offset+icon_img1.shape[0]), font, 1.0, (255, 255, 255), 0)
只是一点 ES6魔法:
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"
}
]
};
第二种优雅方法:
const result = {
favourite_shops: []
};
data.favourite_shops.forEach(el => result.favourite_shops.push(el.shop_id));
答案 1 :(得分:1)
您可以在阵列本身$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"
]
}