简体   繁体   中英

How can I merge two mongo collections?

I am banging my head against the wall on this...

SEE UPDATE 1 (below) !

I am merging two collections together... I looked at this example ( and ~several~ other examples here on SO... )

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#lookup-single-equality

I think I am really close, but my expected results are not the same as what I would expect out of the example.

Here is the schema for 'Event'

const EventSchema = new Schema({
    name: {type: String, required: true},
})

Here is some 'Event' data

[
    {
        "_id": "5e8e4fcf781d96df5c1f5358",
        "name": "358 Event"
    },
    {
        "_id": "5e8e55c5a0f5fc1431453b5f",
        "name": "b5f Event"
    }
]

Here is 'MyEvent' schema:

const MyEventSchema = new Schema({

    userId: {type: Schema.Types.ObjectId, required: true},
    eventId: {type: Schema.Types.ObjectId, required: true},
})

Here is some 'MyEvent' data

[
    {
        "_id": "5e8f4ed2ddab5e3d04ff30b3",
        "userId": "5e6c2dddad72870c84f8476b",
        "eventId": "5e8e4fcf781d96df5c1f5358",
    }
]

Here is my code ( the code is wrapped in a promise so it returns resolve and reject with data )

   var agg = [
       {
         $lookup:
           {
             from: "MyEvent",
             localField: "_id",
             foreignField: "eventId",
             as: "userIds"
           }
       }
    ];

   Event.aggregate(agg)
   .then( events => {
       return resolve(events);
   })
   .catch(err => {
       return reject(null);
   })

Here are my results,

[
    {
        "_id": "5e8e4fcf781d96df5c1f5358",
        "name": "358 Event",
        "__v": 0,
        "UserIds": []
    },
    {
        "_id": "5e8e55c5a0f5fc1431453b5f",
        "name": "b5f Event",
        "__v": 0,
        "UserIds": []
    }
]

I expect to see UserIds filled in for event '358 Event', like this What am I missing???

[
    {
        "_id": "5e8e4fcf781d96df5c1f5358",
        "name": "358 Event",
        "__v": 0,
        "UserIds": [
          {"userId": "5e6c2dddad72870c84f8476b"}
         ]
    },
    {
        "_id": "5e8e55c5a0f5fc1431453b5f",
        "name": "b5f Event",
        "__v": 0,
        "UserIds": []
    }
]

UPDATE 1

I found a mongo playground and what I have works there, but it doesn't work in my code??

https://mongoplayground.net/p/fy-GP_yx5j7

In case the link breaks, here is configuration: * select 'bson multiple collections'

db={
  "collection": [
    {
      "_id": "5e8e4fcf781d96df5c1f5358",
      "name": "358 Event"
    },
    {
      "_id": "5e8e55c5a0f5fc1431453b5f",
      "name": "b5f Event"
    }
  ],
  "other": [
    {
      "_id": "5e8f4ed2ddab5e3d04ff30b3",
      "userId": "5e6c2dddad72870c84f8476b",
      "eventId": "5e8e4fcf781d96df5c1f5358",

    }
  ]
}

Here is Query:

db.collection.aggregate([
  {
    $lookup: {
      from: "other",
      localField: "_id",
      foreignField: "eventId",
      as: "userIds"
    }
  }
])

Here is the result:

[
  {
    "_id": "5e8e4fcf781d96df5c1f5358",
    "name": "358 Event",
    "userIds": [
      {
        "_id": "5e8f4ed2ddab5e3d04ff30b3",
        "eventId": "5e8e4fcf781d96df5c1f5358",
        "userId": "5e6c2dddad72870c84f8476b"
      }
    ]
  },
  {
    "_id": "5e8e55c5a0f5fc1431453b5f",
    "name": "b5f Event",
    "userIds": []
  }
]

any suggestions as to why this doesn't work in my code... but works in the playground?

UPDATE 2

I found this:

Need a workaround for lookup of a string to objectID foreignField

UPDATE 3

I have changed the schema to use ObjectId for ids now still doesn't work

And they are ObjectIds:

在此处输入图像描述

RESOLUTION:

So the real answer was a combination of Update 2 and Update 3 and using the right collection name in the lookup.

Update 2 is pretty much my very same question... just using different table names

Update 3 is the correct way to solve this issue.

Mohammed Yousry pointed out the collection name might be wrong... so I looked at my schema and I did have it wrong - changed the name to the right name (along with ObjectId types) and it worked !

It seems there's a typo in from property in $lookup , MyEvent maybe not the collection name

db.collection.aggregate([
  {
    $lookup: {
      from: "MyEvent", // here is the issue I think, check the collection name and make sure that it matches the one you write here
      localField: "_id",
      foreignField: "eventId",
      as: "userIds"
    }
  }
])

in mongo playground you attached in the question, if you change the 'other' in the $lookup to anything else, or make a typo in it.. like others instead of other , you will face the same issue

so check that there is no typo in the word MyEvent that you populate from

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