简体   繁体   中英

mongo: multiple queries or not?

I'm wondering the best way to query mongo db for many objects, where each one has an array of _id's that are attached to it. I want to grab the referenced objects as well. The objects' schemas looks like this:

var headlineSchema = new Schema({
    title : String, 
    source : String,
    edits : Array       // list of edits, stored as an array of _id's
    ...
});

...and the one that's referenced, if needed:

var messageSchema = new Schema({
    message : String,
    user : String,
    headlineID : ObjectId   // also contains a ref. back to headline it's incl. in
    ...
});

One part of the problem (well, depending if I want to keep going this route) is that pushing the message id's is not working (edits remains an empty array [] afterwards) :

db.headline.update({_id : headlineid}, {$push: {edits : messageid} }, true);

When I do my query, I need to grab about 30 'headlines' at a time, and each one could contain references to up to 20 or 30 'messages'. My question is, what is the best way to fetch all of these things? I know mongo isn't a relational db, so what I'm intending is to first grab the headlines that I need, and then loop through all 30 of them to grab any attached messages.

db.headline.find({'date': {$gte: start, $lt: end} }, function (err, docs) {
    if(err) { console.log(err.message); }
    if(docs) { 
        docs.forEach(function(doc){
            doc.edits.forEach(function(ed){
                db.messages.find({_id:ed}, function (err, msg) {
                    // save stuff
                });
            });
        });
    }
});

This just seems wrong, but I'm unsure how else to proceed. Should I even bother with keeping an array of attached messages? I'm not married to the way I've set up my schema, either. If there is a better way to track relationships between them, or a better query to achieve this, please let me know. Thanks

Does each message belong to only one headline? If so, you can store the headline id as part of each message. Then for each headline, do:

db.messages.find({headline_id: current-headline-id-here})

You could try using the $in operator for selecting a list of ObjectIds

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24in

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