MongoDB:返回空数组的 ObjectId 之间的聚合 $lookup
MongoDB: aggregation $lookup between ObjectIds returning an empty array
我正在尝试使用 $lookup 在两个 ObjectId
类型的字段之间执行聚合。我已经检查了我的数据,它应该会返回一些东西。此外,模式确实将字段定义为 ObjectId,因此如果我没记错的话,我不需要像我在某些帖子中看到的那样转换数据类型。这是我的查询:
db.workerlocationcontexts.aggregate([
{
$lookup: {
from: "LocationSensors",
localField: "sensor",
foreignField: "_id",
as: "test"
}
}
])
这是我的 collections/sample 数据:
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
}
我得到的结果都是我的 WorkerLocationContexts
,但是字段“test”returns 是一个空数组。
有人可以帮助我吗?
提前致谢!
from
字段到 $lookup
似乎区分大小写,因此在该字段中输入集合名称是一个常见问题。
一个常见的问题是在使用 mongoose 时没有添加最后的“s”。 Os,在这种情况下,使用大写字母,哟使用 from: locationsensors
应该像 this example
from
字段必须与集合名称相同,否则Mongo找不到所需的集合。
我正在尝试使用 $lookup 在两个 ObjectId
类型的字段之间执行聚合。我已经检查了我的数据,它应该会返回一些东西。此外,模式确实将字段定义为 ObjectId,因此如果我没记错的话,我不需要像我在某些帖子中看到的那样转换数据类型。这是我的查询:
db.workerlocationcontexts.aggregate([
{
$lookup: {
from: "LocationSensors",
localField: "sensor",
foreignField: "_id",
as: "test"
}
}
])
这是我的 collections/sample 数据:
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 }
我得到的结果都是我的 WorkerLocationContexts
,但是字段“test”returns 是一个空数组。
有人可以帮助我吗?
提前致谢!
from
字段到 $lookup
似乎区分大小写,因此在该字段中输入集合名称是一个常见问题。
一个常见的问题是在使用 mongoose 时没有添加最后的“s”。 Os,在这种情况下,使用大写字母,哟使用 from: locationsensors
应该像 this example
from
字段必须与集合名称相同,否则Mongo找不到所需的集合。