给定集合中的以下布局...
{
vehicle_id: 1
,// bunch of properties I don't want
,vehicle: {
mfg_year: 1928
,mfg_make: "Ford"
,mfg_model: "Model A"
,mfg_trim: "T-Bucket"
,// bunch of properties I don't want
,images: [
{url:'...',...}
,...
]
}
}
如何返回只有上述字段的结果,并且只有图像下的第一个结果?我不介意结果是否在一个扁平对象中,只有图像是嵌套对象。
我查看了聚合框架,它似乎与我正在寻找的不符。我知道我可以对结果集进行 map/reduce,或者对 listing_id 进行分组,我只是希望有一个更简单的查询结构,而不需要求助于分组或 reduce。
如果目前通过聚合框架无法做到这一点,工作组或 map-reduce 将是一个可以接受的答案。
编辑:最终结果中有大约 50 多个我不想要的属性。使用 $slice 指令,似乎我不能只指定我想要的字段。
最佳答案
怎么样:
db.vehicles.find({"vehicle_id":1}, {images:{$slice: 1}})
示例
db.vehicles.insert({"vehicle_id": 1, "mfg_year": "1928", "mfg_make": "Ford", "mfg_model": "Model A", "images": [{"url":"www.a.com"}, {"url":"www.b.com"}, {"url":"www.c.com"}]})
db.vehicles.insert({"vehicle_id": 2, "mfg_year": "1999", "mfg_make": "BMW", "mfg_model": "Model B", "images": [{"url":"www.a.com"}, {"url":"www.b.com"}, {"url":"www.c.com"}]})
db.vehicles.insert({"vehicle_id": 3, "mfg_year": "1998", "mfg_make": "FMerc", "mfg_model": "Model C", "images": [{"url":"www.a.com"}, {"url":"www.b.com"}, {"url":"www.c.com"}]})
//now the query
db.vehicles.find({"vehicle_id":1}, {images:{$slice: 1}})
输出:
{
"vehicle_id" : 1,
"mfg_year" : "1928",
"mfg_make" : "Ford",
"mfg_model" : "Model A",
"images" : [
{
"url" : "www.a.com"
}
]
}
编辑
您可以像这样仅指定要返回的字段:
db.vehicles.find({"vehicle_id":1}, {"mfg_make":1, images:{$slice: 1}})
因此,在这种情况下,仅返回 mfg_make
和 images
。
另一个....
db.vehicles.find({"vehicle_id":1}, {"mfg_make":1, "some_other_field":1, images:{$slice: 1}})
如果这是一个 RDBMS,这个查询等同于:
SELECT mfg_make, some_other_field FROM tblVehicles WHERE vehicle_id = 1
关于mongodb - 仅获取 mongodb 中数组属性的第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13459195/