db.absences.insert([
{ "_id" : 1, "student" : "Ann Aardvark", sickdays: [ new Date ("2018-05-01"),new Date ("2018-08-23") ] },
{ "_id" : 2, "student" : "Zoe Zebra", sickdays: [ new Date ("2018-02-01"),new Date ("2018-05-23") ] },
])
db.holidays.insert([
{ "_id" : 1, year: 2018, name: "New Years", date: new Date("2018-01-01") },
{ "_id" : 2, year: 2018, name: "Pi Day", date: new Date("2018-03-14") },
{ "_id" : 3, year: 2018, name: "Ice Cream Day", date: new Date("2018-07-15") },
{ "_id" : 4, year: 2017, name: "New Years", date: new Date("2017-01-01") },
{ "_id" : 5, year: 2017, name: "Ice Cream Day", date: new Date("2017-07-16") }
])
db.absences.aggregate([
{
$lookup:
{
from: "holidays",
pipeline: [
{ $match: { year: 2018 } },
{ $project: { _id: 0, date: { name: "$name", date: "$date" } } },
{ $replaceRoot: { newRoot: "$date" } }
],
as: "holidays"
}
}
])
我正在尝试在查找聚合查询时使用管道。与Mongodb文档中的相同,它仍然会出错
Unable to execute the selected commands
Mongo Server error (MongoCommandException): Command failed with error 4570: 'arguments to $lookup must be strings, pipeline: [ { $match: { year: 2018.0 } }, { $project: { _id: 0.0, date: { name: "$name", date: "$date" } } }, { $replaceRoot: { newRoot: "$date" } } ] is type array' on server localhost:27017.
The full response is:
{
"ok" : 0.0,
"errmsg" : "arguments to $lookup must be strings, pipeline: [ { $match: { year: 2018.0 } }, { $project: { _id: 0.0, date: { name: \"$name\", date: \"$date\" } } }, { $replaceRoot: { newRoot: \"$date\" } } ] is type array",
"code" : NumberInt(4570),
"codeName" : "Location4570"
}
我正在使用mongodb v3.4。
答案 0 :(得分:21)
因为您尝试在 MongoDB v3.4
上使用 MongoDB v3.6 中的$lookup
功能(语法)
MongoDB v3.4 $lookup
语法:
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
MongoDB v3.6 $lookup
语法:
{
$lookup:
{
from: <collection to join>,
let: { <var_1>: <expression>, …, <var_n>: <expression> },
pipeline: [ <pipeline to execute on the collection to join> ],
as: <output array field>
}
}
https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
答案 1 :(得分:-2)
在$ lookup中,您可以在查找之后加入collectionfirst并进行匹配,项目等。你应该有一个涉及假期集合的外国领域。
喜欢:
{
$lookup:
{
from: "holidays",
localField: "holidaysID", //yourLocalfield, it is local field in absences. you should have it to join 2 collections
foreignField : "_id", //theforeignfield, it is _id in the holidays
as: "holidays"
}
},{ $match: { year: 2018 } },
{ $project: { _id: 0, date: { name: "$name", date: "$date" } } },
{ $replaceRoot: { newRoot: "$date" } }
希望它有所帮助。