如何找到有条件的数据?我需要该条件仅与dpt
属性中的最后一个匹配。我需要检查上次departmentID
说xyz
这是我的DB:
{
"_id" : ObjectId("56b08ceb19e01cd3240fc1ff"),
"empCode" : "vss815",
"firstName" : "ashu123",
"lastName" : "kashyap",
"status" : true,
"dpt" : [
{
"departmentID" : ObjectId("56b0402a92b2a18116bf51de"),
"effFrom" : ISODate("2016-02-02T11:03:07.972Z")
},
{
"departmentID" : ObjectId("56b32c40e11ac0222034956c"),
"effFrom" : ISODate("2016-02-04T10:48:04.406Z")
},
{
"departmentID" : ObjectId("56b32c3ee11ac0222034956b"),
"effFrom" : ISODate("2016-02-17T09:02:38.148Z")
}
],
}
我正在尝试的是:
objMdlEmp.find({ 'dpt.departmentID':id } , {} , {'dpt.$' : 1})
.populate('dpt.departmentID')
.exec(function (err, result){
if(!err){
callback(true , result);
}
});
但它从所有dpt
数组中找到。
答案 0 :(得分:0)
请尝试使用$unwind
,$sort
和$group
来执行此操作:
objMdlEmp.aggregate([
{$unwind: '$dpt'},
// Sort the by effFrom
{$sort: {'dpt. effFrom': -1}},
// Group by effFrom, taking the first dept
{$group: {
_id: { effFrom: '$effFrom' },
dpt: {$first: '$dpt'}
}}
// Shape back to the original style
{$project: {_id: 1, dpt: 1}}
],
function(err, rets) {
objMdlEmp.populate( rets, { "path": "dpt.departmentID" },
function(err,results) {
//
});