简体   繁体   中英

How to join array of documents from array of _ids in mongoDB

I have a document inside of MongoDb that has an array of ObjectIds. Looks like this:

--Shops Collection--

listing_ids: [
ObjectId("6092f741ccb0d55ba444883e"),
ObjectId("6092f741ccb0d55ba444883f"),
ObjectId("6092f741ccb0d55ba4448840"),
ObjectId("6092f741ccb0d55ba4448841")
],
...

and I have a listing document like this:

--Listings Collection--

_id: ObjectId("6092f741ccb0d55ba444883e"),
...

How do I join the listings documents onto the shops document that contains the arrays? I have tried the "$lookup" operator from MonogoDb but can't get it to work. I'm always hit with a FailedToParse error. This is what the "$lookup" looks like:

const collection = client.db("development").collection("shops");

    const shop = await collection.aggregate([
      { 
        "$lookup": {
        "from": "listings",
        "localfield": "listing_ids",
        "foreignField": "_id",
        "as": "listings"
      }}
    ]).toArray();

This is expected to return all of the shops documents with the corresponding listings documents in an array called listings

Turns out I almost had it right. I ended up using the MongoDB Atlas Aggregation tool and it helped me. This is the working pipeline:

.aggregate([
        {
          '$lookup': {
            'from': 'listings', 
            'localField': 'listing_ids', 
            'foreignField': '_id', 
            'as': 'listings'
          }
        }, {
          '$lookup': {
            'from': 'listings', 
            'localField': 'highlightedListings', 
            'foreignField': '_id', 
            'as': 'highlightedListings'
          }
        }
      ]).toArray();

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