mongodb( 實現join)


mongodb提供ref和populate的方法,支持類似join的SQL操作。本文給出一個實際的例子:

1. 數據1:

var daob = new Schema({

    user: {
        type: String
    },
    title: {
        type: String
    },
    tag: [{
        type: String
    }],
    content: {
        type: String
    },
    count: {
        type: Number,
        'default':0
    }
});

2. 數據2:

var daoa = new Schema({

    name: {
        type: String
    },
    time: {
        type: Date
    },
    conments: [{
        type: mongoose.Schema.ObjectId, //這里保存daob的id,mongo中只能使用collection的_id
        ref: 'daob'
    }]
});

3. 插入操作:

var b = new daobmodel({
        user: 'fredric',
        title: 'title1',
        tag: ['tag1', 'tag2', 'tag3'],
        content: 'nothing to say, just test',
    });

    b.save(function(err) {
        var a = new daoamodel({
            name: 'sinny',
            time: new Date(),
            conments: [b._id]
        });

        a.save(function(err) {
            return callback(err);
        })
    });

4. 查找操作:

mongo不支持真正意義上的join操作,因此本例中的需求只能分拆成兩步

//這里可以采用聚合來實現比較復雜的查詢
    daobmodel.find({
        'tag': {
            $in: ['tag1']
        }
    }, {
        _id: 1
    }, function(err, ids) {
        daoamodel.find({
            conments: {
                $in: ids
            }
        }).populate('conments').exec(function(err, docs) {
            return callback(err, docs);
        });
    });


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM