我想从我的查询和预期结果中仅过滤kumar“to”item "_id" : ObjectId("5048d2e5fbdac48208000042")
消息
{
"_id" : ObjectId("5191502a2f1b3ca33e000016"),
"message" : "<p>sssdasd<br></p>",
"subject" : "test message to nag",
"date" : ISODate("2013-05-13T20:42:19.349Z")
}
来自以下馆藏
{
"__v" : 0,
"_id" : ObjectId("5191502a2f1b3ca33e000016"),
"conversation" : [
{
"date" : ISODate("2013-05-13T20:42:19.349Z"),
"message" : "<p>sssdasd<br></p>",
"_id" : ObjectId("5191502a2f1b3ca33e000017"),
"to" : {
"_id" : ObjectId("5048d2e5fbdac48208000042"),
"name" : "Kumar"
},
"from" : {
"_id" : ObjectId("503fdbfa294f6db74de649ea"),
"name" : "Anand"
}
},
{
"message" : "<p>reply</p>",
"date" : ISODate("2013-05-13T21:05:33.453Z"),
"_id" : ObjectId("5191559c7d2c386741000018"),
"to" : {
"_id" : ObjectId("503fdbfa294f6db74de649ea"),
"name" : "Anand"
},
"from" : {
"_id" : ObjectId("5048d2e5fbdac48208000042"),
"name" : "Kumar"
}
},
{
"message" : "<p>reply2<br></p>",
"date" : ISODate("2013-05-13T21:05:55.006Z"),
"_id" : ObjectId("519155b1ca98b66641000014"),
"to" : {
"_id" : ObjectId("503fdbfa294f6db74de649ea"),
"name" : "Anand"
},
"from" : {
"_id" : ObjectId("503fdbfa294f6db74de649ea"),
"name" : "Anand"
}
}
],
"from" : {
"_id" : ObjectId("503fdbfa294f6db74de649ea"),
"name" : "Anand"
},
"sent" : ISODate("2013-05-13T20:42:19.349Z"),
"subject" : "test message to nag",
"to" : {
"_id" : ObjectId("5048d2e5fbdac48208000042"),
"name" : "Kumar"
}
}
我尝试使用以下查询
db.messages.find({'conversation.to._id':ObjectId("5048d2e5fbdac48208000042")},{'subject':-1, 'conversation.message': 1,'conversation.to':1}).pretty();
但我没有得到预期的结果
答案 0 :(得分:0)
我使用了聚合框架我能够得到预期的结果。
db.message.aggregate(
{ $unwind : "$conversation" },
{ $match: {
"conversation.to.name" : "Anand"
}
},
{
$sort: {
"conversation.date" : -1
}
},
{
$group: {
_id:"$_id",
msgSubject: {$first:"$subject"},
msgDate: {$first:"$conversation.date"},
latestmsg: {$first:"$conversation.message"}
}
}
);
如果不同于以上
,请分享