Search code examples
mongodbmongodb-querymongodb-compass

How to export across collection?


I would like to export information across collection. For example, I have 2 collection User and Orders. User contains login info(username) and orders contains the orderID. So when a customer purchases something, the orderID will be generated in the Orders collection and their userID(not the same as username) will be recorded in the order. So I have to reference the userID to find the username within User collection.

I would like to export the orderID alongside the username. Is that possible? As it currently stands, mongodb compass has the export button only when you've selected the collection.


Solution

  • for example your user collection is like this users collection

    [{
    _id:123,
    username:example,
    }]
    

    orders collection

    [{
    _id:234
    userId : ObjectId('123')
    orderPrice : 300
    }]
    

    so you could get order in user object like this with $lookup

    db.orders.aggregate([
    {
            '$lookup': {
                'from': 'users', // users collection 
                'localField': 'userId', 
                'foreignField': '_id', 
                'as': 'order'
            }
    ])