Home > front end >  MongoDB: aggregation $lookup between ObjectIds returning an empty array
MongoDB: aggregation $lookup between ObjectIds returning an empty array

Time:02-15

I'm trying to perform an aggregation using $lookup between two fields of type ObjectId. I've already checked my data and it should be returning something. Also, the schemas indeed define the fields as ObjectId, so if I am not mistaken I should not need to convert the data type as I've seen in some posts. Here's my query:

db.workerlocationcontexts.aggregate([ 
    {
        $lookup: {
            from: "LocationSensors",
            localField: "sensor",
            foreignField: "_id",
            as: "test"
        }
    }
])

Here are my collections/sample data:

  • WorkerLocationContexts

    {
      "_id":{"$oid":"615676c885ccad55a493503b"},
      "updatedAt":{"$date":"2021-10-01T02:47:36.207Z"},
      "createdAt":{"$date":"2021-10-01T02:47:36.207Z"},
      "sensor":{"$oid":"6181e5f83fca98374cf901fd"},
      "worker":{"$oid":"6153dcfb58ad722c747eb42d"},
      "__v":0
    }
    
  • LocationSensor

    {
      "_id":{"$oid":"6181e5f83fca98374cf901fd"},
      "name":"Location Sensor 1",
      "description":"Location sensor for Location 2",
      "location": "$oid":"6181df3b3fca98374cf901fb"},
      "trackerType":"RFID",
      "sensorType":"ENVIRONMENT",
      "type":"LOCATION",
      "__v":0
    }
    

The result I'm getting are all my WorkerLocationContexts, but the field "test" returns as an empty array.

Can someone help me?

Thanks in advance!

CodePudding user response:

from field into $lookup seems to be case sensitive so it is a common problem the collection name typed in that field.

One common problem is not add the final "s" while using mongoose. Os, as in this case, the use of capital letters, yo using from: locationsensors should works like this example

The from field has to be the same as the collection name, otherwise Mongo can't find the desired collection.

  • Related