2014-05-25 68 views
0
/* 0 */ 
{ 
    "_id" : ObjectId("5380c9e097632cee5b000007"), 
    "month" : "5", 
    "userid" : "53806aac12c75f4b51000001", 
    "__v" : 7, 
    "posts" : [{ 
     "postid" : ObjectId("538185cae0c6b8666e000008"), 
     "ts" : ISODate("2014-05-25T05:55:22.976Z"), 
     "userid" : "53806aac12c75f4b51000001", 
     "name" : "BBB", 
     "text" : "b1", 
    }] 
} 

/* 1 */ 
{ 
    "_id" : ObjectId("5380c80e97632cee5b000001"), 
    "month" : "5", 
    "userid" : "5380629ea3b31f864f000001", 
    "__v" : 24, 
    "posts" : [{ 
     "postid" : ObjectId("538185b2e0c6b8666e000004"), 
     "ts" : ISODate("2014-05-25T05:54:58.703Z"), 
     "userid" : "5380629ea3b31f864f000001", 
     "name" : "AAA", 
     "text" : "a1", 
    }, { 
     "postid" : ObjectId("538185b7e0c6b8666e000006"), 
     "ts" : ISODate("2014-05-25T05:55:03.474Z"), 
     "userid" : "5380629ea3b31f864f000001", 
     "name" : "AAA", 
     "text" : "a2", 

    }, { 
     "postid" : ObjectId("538185d6e0c6b8666e00000a"), 
     "ts" : ISODate("2014-05-25T05:55:34.231Z"), 
     "userid" : "5380629ea3b31f864f000001", 
     "name" : "AAA", 
     "text" : "a3", 
    }] 
} 

這是我的數據。如何在MongoDB中對這些數據進行排序?

我想爲'Ts'(數據)排序此數據。

我想,排序清單由 'posts.Ts' 這樣的..
名稱:AAA,文本= A3
名稱:BBB,文本= B1
名稱:AAA,文本= A2
名稱: AAA,text = a1

但我不知道如何查詢這個。請與我聯繫

這是我在Node和mongoose中的代碼。

db.collection('walls', function(err, collection) { 

collection.find(function(err, data) { 

collection.aggregate(
{$match: {userid:userid}}, 
{$project: {posts: 1,_id:0}}, 
{$sort:{'posts.ts':1}}, 
{$unwind: "$posts"} 
)} 

...

回答

0

您是在正確的原則,但你必須圍繞管道階段走錯了路。排序前需要$unwind陣列:

db.collection.aggregate([ 
    { "$match": { "userId": userId" } }, 
    { "$project": { "_id": 0, "posts": 1 } }, 
    { "$unwind": "$posts" }, 
    { "$sort": { "posts.ts": 1, "posts.name": 1 } } 
]) 
相關問題