1

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!

2
  • 1
    Check the collection name and ensure is LocationSensors. Or change the lookup to colletction name, maybe locationsensors. The query should works Commented Feb 13, 2022 at 0:31
  • 1
    Hi @J.F., you are right! The collection name was correct, but apparently it is case sensitive! Just changed the letters and it worked... Can you post it as an answer so I can set it as solved? Commented Feb 13, 2022 at 0:58

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.