我想在ObjectId
中使用一些let
,但每次都出现相同的错误:
Failed to execute script.
Error: invalid object id: length
Details:
@(shell):6:36
我的查询:
db.projects.aggregate([
{$lookup: {
from: 'pointValueChangements',
let: {id: '$_id'},
pipeline: [
{ $match: { projectId: new ObjectId('$$id'), date: {$lte: new Date()}}},
{ $sort: { date: -1}},
{ $limit: 1},
],
as: 'pointValue',
}},
{$project: {pointValue: 1}}
])
如果我将new ObjectId('$$id')
替换为'$$id'
,则查询工作正常,但结果不好。
如果我将'$$id'
替换为ObjectId(someMongoId)
,一切都很好(但是不好,因为此ID仅匹配一行...)
答案 0 :(得分:2)
Try this query
db.projects.aggregate([
{$lookup: {
from: 'pointValueChangements',
let: {id: '$_id'},
pipeline: [
{ $match: {
$expr:
{
$and:
[
{ $eq: ['$projectId', '$$id'] },
{ date: {$lte: new Date() }},
],
},
}},
{ $sort: { date: -1}},
{ $limit: 1},
],
as: 'pointValue',
}},
{$project: {pointValue: 1}}
])