例如我要获得所有的name字段集合['bob', 'ahn', 'abc'],该怎么写sql
{
"_id" : 2,
"name" : "bob",
"age" : 42,
"type" : 1,
"status" : "A",
"finished" : [ 11, 25 ],
"badges" : [ "green" ]
}
{
"_id" : 3,
"name" : "ahn",
"age" : 22,
"type" : 2,
"status" : "A",
"finished" : [ 6 ],
"badges" : [ "blue", "red" ]
}
{
"_id" : 6,
"name" : "abc",
"age" : 43,
"type" : 1,
"status" : "A",
"finished" : [ 18, 12 ],
"badges" : [ "black", "blue" ]
}
巴扎黑2017-04-17 15:03:44
不管透過何種方式,資料庫給你的結果只會是:
[{name: 'bob'},
{name: 'ahn'},
{name: 'abc'}]
如果是在shell下面,可以用JS腳本轉換:
var cursor = db.coll.find({}, {_id: 0, name: 1});
var result = cursor.map(function(doc) {
return doc.name;
});
這裡用到cursor.map方法。在不同的驅動中應該都有不同的實作。但這部分工作其實不是資料庫為你完成的,而是驅動在app端做的轉換。資料庫是緊要資源,在不影響效能的前提下應該盡可能把消耗資源的行為都放到應用端。因為相較於資料庫,應用的水平擴展要容易且成本更低。