2014-09-19 66 views
2

所以我想排序子文檔,但也選擇和一切。看來我不能用常規查詢,所以我嘗試瓦特/ aggregate如何排序,選擇和查詢貓鼬中的子文檔

mongoose = require("mongoose"); 
mongoose.connect("localhost:27017", function(err) { 
    mongoose.connection.db.dropDatabase(); 
    Story = mongoose.model("Story", { 
    title: String, 
    comments: [{ 
     author: String, 
     content: String 
    }] 
    }); 
    sample = new Story({ 
    title: "Foobar", 
    comments: [ 
    { 
     author: "A author", 
     content: "1 Content" 
    }, 
    { 
     author: "B author", 
     content: "2 Content" 
    } 
    ] 
    }); 
    sample.save(function(err, doc) { 
    Story.aggregate([ 
     { $match: { 
      _id: doc._id 
     }}, 
     { $unwind: "$comments" }, 
     { $project: {"comments": 1}}, 
     { $sort: {"comments.author": -1}} 
    ], function (err, result) { 
     if (err) { 
      console.log(err); 
      return; 
     } 
     console.log(result); 
    }); 
    }) 
}); 

這幾乎工作:

[ { _id: 541c0f8098f85ac41c240de4, 
    comments: 
    { author: 'B author', 
     content: '2 Content', 
     _id: 541c0f8098f85ac41c240de5 } }, 
    { _id: 541c0f8098f85ac41c240de4, 
    comments: 
    { author: 'A author', 
     content: '1 Content', 
     _id: 541c0f8098f85ac41c240de6 } } ] 

但我想什麼:

[ { author: 'B author', 
    content: '2 Content', 
    _id: 541c0f8098f85ac41c240de5 }, 
{ author: 'A author', 
    content: '1 Content', 
    _id: 541c0f8098f85ac41c240de6 } ] 

我可以使用lodash的pluck,但有沒有辦法只用mongodb來做到這一點?

回答

2

你可以改變你的$project也重塑輸出,以提供你正在尋找的結構:

Story.aggregate([ 
    { $unwind: "$comments" }, 
    { $project: { 
     author: '$comments.author', 
     content: '$comments.content', 
     _id: '$comments._id' 
    }}, 
    { $sort: {author: -1}} 
], function (err, result) { ... 

輸出:

[ { _id: 541c2776149002af52ed3c4a, 
    author: 'B author', 
    content: '2 Content' }, 
    { _id: 541c2776149002af52ed3c4b, 
    author: 'A author', 
    content: '1 Content' } ] 
+0

偉大工程的感謝!有沒有辦法自動做到這一點?沒有指定字段? – Vinz243 2014-09-19 16:11:57

+0

@ Vinz243不需要,您需要單獨命名投影中的每個字段,因爲您希望它們位於頂層。 – JohnnyHK 2014-09-19 16:54:58

+0

我看到謝謝你! – Vinz243 2014-09-19 16:55:19