$nin mongodb not giving me the results I expect

时间:2018-04-26 16:58:42

标签: mongodb aggregate

I am doing a query on some data in an appearances collection that looks like this.

[
{
    "yearID" : 1871,
    "teamID" : "BS1",
    "masterID" : "barnero01"
},
{
    "yearID" : 1871,
    "teamID" : "BS1",
    "masterID" : "barrofr01"
},
{
    "yearID" : 1871,
    "teamID" : "BS1",
    "masterID" : "birdsda01"
},
{
    "yearID" : 1958,
    "teamID" : "LAN",
    "masterID" : "bessedo01"
},
{
    "yearID" : 1955,
    "teamID" : "BRO",
    "masterID" : "bessedo01"
},
{
    "yearID" : 2002,
    "teamID" : "LAN",
    "masterID" : "alvarvi01"
},
{
    "yearID" : 1966,
    "teamID" : "LAN",
    "masterID" : "barbiji01"
}
]

(There are 98000 entries) I want to get a distinct list of all the masterIDs of all the players with the teamID of 'LAN' but who have also never be associated with a different teamID other than 'LAN'. So it would only return the last two entries. My thought was to do a match and get all the masterIDs where the team id is not 'lan' and then do a $nin operation to get all the entries not in that set. I would then return the masterID as shown and hopefully get the results. However, if I just leave the

{teamID:{$ne:'LAN'} 

part and take out the $nin, it returns the same results which tells me it's not working.

var nonLANPlayers = [];
db.appearances.find({teamID: {$ne:"LAN"}}).sort({masterID:1}).forEach(function(player){
    nonLANPlayers.push(player.masterID);
});
db.appearances.aggregate(
{
    $group: {_id:"$masterID"}
},
{
    $match: {masterID:{$nin:nonLANPlayers}}
},{
    $sort: {_id:1}
});

I am really close, any ideas why the $nin is not working for me?

1 个答案:

答案 0 :(得分:0)

我经过一系列的试验和错误后自己修好了。结果在mongodb聚合函数中你必须在$ group之前得到$ match,我反过来了。我会把它留在这里,以防它帮助其他人。