简体   繁体   中英

How do I select fields in difference collections MongoDB

One of my fields needs to hold a total score which it gets by adding the scores from a different collection ( Players ). Each player has a field for its scores. I understand that I could get the ids of each player but how would I only get the score field?

The structure is something like this:

db.players.insert({
 name: 'Bob',
 score: 30,
});

db.players.insert({
 name: 'Emily',
 score: 50,
});

db.totalscores.insert({
 total: "calculate score"*
)};

That is called projection .

you can do a simple find({your search critieria}, {field projection})

example would be

db.players.find({},{score:1, _id:0})

this will return only score field.like this

{ "score" : 30 }
{ "score" : 50 }

but a nicer alternative would be to use aggregate and calculate the score directly

db.players.aggregate([ { 
    $group: { 
        _id: null, 
        total: { 
            $sum: "$score" 
        } 
    } 
} ] )

this will return

{ "_id" : null, "total" : 80 }

you can also get rid of the ID from the output by simply including a $project stage and setting _id to 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM