简体   繁体   中英

How to query multiple collections in mongodb (without using $lookup)?

I would like to create a single query that gets data from three different collections from providing a single query parameter. I have seen methods that use $lookup but I do not want to use that as I cannot use it on sharded collections.

Here is an example to explain further.

I have three collections: user, chatroom and chatMessage.

user collection:

{
    _id: ObjectId('456'),
    username: 'John',
    contacts: [
        {
            _id: ObjectId('AB12'),
            name: 'Mary',
            idOfContact: ObjectId('123'),
        },
        {
            _id: ObjectId('AB34'),
            name: 'Jane',
            _idOfContact: ObjectId('234'),
        },
        {
            _id: ObjectId('AB56'),
            name: 'Peter',
            _idOfContact: ObjectId('345'),
        }
    ],
}

chatroom collection:

{
    _id: ObjectId('AB34'),
    usersInThisChatRoom: [
        ObjectId("456"),
        ObjectId("123"),
        ObjectId("234"),
    ]
}

chatMessage collection:

[
    {
        _id: ObjectId("M01"),
        chatRoomObjectId: _id: ObjectId('AB34'),
        senderObjectId: ObjectId('456'),
        message: 'Hello humans!',
        date: ISODate("2019-09-03T07:24:28.742Z"),
    },
    ...(other messages)
]

What I would like to be returned

[
    {
        chatRoomObjectId: ObjectId('AB34'),
        usersInThisChatRoom: [
            {
                contactName: 'John',
                contactUserId: ObjectId('456'),
            },
                contactName: 'Mary',
                contactUserId: ObjectId('123'),
            },
                contactName: 'Jane',
                contactUserId: ObjectId('234'),
            }
        ]
        chatMessages: [
            {
                _id: ObjectId("M01"),
                senderObjectId: ObjectId('456'),
                message: 'Hello humans!',
                date: ISODate("2019-09-03T07:24:28.742Z"),
            },
            ...(other messages)
         ]
    },  
    ...(other documents)
]

Is there a way to get my desired results by making a single query using the user._id and will that be performance friendly?

Or, do I have to make several queries, one after another, to achieve what I want?

According to this answer , you cannot perform a single query across multiple collections (aside from the $lookup aggregation pipeline function.

This means that You either use the $lookup aggregation pipeline or you make several queries to the DB.

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