2013-10-04 124 views
7

我在MongoDB中有以下數據(對於我的問題需要什麼簡化)。MongoDB查詢查找數組第一個元素的屬性

{ 
    _id: 0, 
    actions: [ 
     { 
      type: "insert", 
      data: "abc, quite possibly very very large" 
     } 
    ] 
} 
{ 
    _id: 1, 
    actions: [ 
     { 
      type: "update", 
      data: "def" 
     },{ 
      type: "delete", 
      data: "ghi" 
     } 
    ] 
} 

我想要的是找到每個文檔的第一個動作類型,例如,

{_id:0, first_action_type:"insert"} 
{_id:1, first_action_type:"update"} 

(這很好,如果結構不同的數據,但我需要這些值存在,不知何故。)

編輯:我試過db.collection.find({}, {'actions.action_type':1}),但很明顯,它返回動作陣列的所有元素。

NoSQL對我來說是相當新的。之前,我會將所有這些數據存儲在關係數據庫的兩個表格中,並執行類似SELECT id, (SELECT type FROM action WHERE document_id = d.id ORDER BY seq LIMIT 1) action_type FROM document d的操作。

+1

只是'... actions [0]'用於'collection .find方法' –

+0

這些文件很大......我正在尋找使用投影或其他東西來幫助我獲得我需要的東西。 –

+0

你可以添加索引 –

回答

11

可以在投影使用$slice操作。 (但是對於你所做的事我不確定當你更新它時陣列的順序是否保持不變)

db.collection.find({},{'actions':{$slice:1},'actions.type':1}) 
1

您還可以使用在2.2版本中引入的Aggregation Pipeline

db.collection.aggregate([ 
    { $unwind: '$actions' }, 
    { $group: { _id: "$_id", first_action_type: { $first: "$actions.type" } } } 
]) 
+0

它會回饋整個陣列,需要在團隊之前放鬆一下。像這樣:db.collection.aggregate([{$ unwind:'$ actions'},{$ group:{_id:「$ _id」,first_action_type:{$ first:「$ actions.type」}}}]) – attish

+0

語法錯誤:'{「$ actions.type」}' –

+0

@PaulDraper對不起有一個錯字。修正了,你可以試試:) – Agis