我有文档和参数,我正在尝试构建一个查询来选择与参数匹配的文档。
document {
_id : ...,
status : ...,
type : ...,
...
}
parameter {
_id : ...,
parameter : ...,
status : ...,
type : ...,
}
我确实认为 SQL 会害死我。 我该怎么办:
select document.* from document,parameter
where document.type = parameter.type and document.status = parameter.status
and parameter.parameter="example"
我可能不认为这是正确的方法,例如:我不使用两个对象之间的任何引用链接,我可能会这样做,但它会是一个 N 到 N 的链接,而且我觉得它不容易维护,因为参数或文档会更新。
最佳答案
请尝试以下查询:
db.document.aggregate([
{
$lookup:
{
from: "parameter",
let: { type: "$type", status: "$status" },
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ "$parameter", "example" ] },
{ $eq: [ "$type", "$$type" ] },
{ $eq: [ "$status", "$$status" ] }
]
}
}
}
],
as: "documentParameterJoined"
}
}
])
文档收集数据:
/* 1 */
{
"_id" : ObjectId("5e160929627ef782360f69aa"),
"status" : "mystatus",
"type" : "whattype"
}
/* 2 */
{
"_id" : ObjectId("5e160931627ef782360f6abb"),
"status" : "mystatus1",
"type" : "whattype1"
}
参数收集数据:
/* 1 */
{
"_id" : ObjectId("5e16095f627ef782360f6e1d"),
"parameter" : "example",
"status" : "mystatus",
"type" : "whattype"
}
/* 2 */
{
"_id" : ObjectId("5e16097e627ef782360f70b5"),
"parameter" : "example",
"status" : "mystatus1",
"type" : "whattype1"
}
/* 3 */
{
"_id" : ObjectId("5e160985627ef782360f7152"),
"parameter" : "example1",
"status" : "mystatus",
"type" : "whatType"
}
/* 4 */
{
"_id" : ObjectId("5e160a39627ef782360f8027"),
"parameter" : "example",
"status" : "mystatus1",
"type" : "whatType"
}
/* 5 */
{
"_id" : ObjectId("5e160a42627ef782360f80ec"),
"parameter" : "example",
"status" : "mystatus",
"type" : "whatType1"
}
结果:
// You don't see docs 3 to 5 as they don't match any filter criteria.
/* 1 */
{
"_id" : ObjectId("5e160929627ef782360f69aa"),
"status" : "mystatus",
"type" : "whattype",
"documentParameterJoined" : [
{
"_id" : ObjectId("5e16095f627ef782360f6e1d"),
"parameter" : "example",
"status" : "mystatus",
"type" : "whattype"
}
]
}
/* 2 */
{
"_id" : ObjectId("5e160931627ef782360f6abb"),
"status" : "mystatus1",
"type" : "whattype1",
"documentParameterJoined" : [
{
"_id" : ObjectId("5e16097e627ef782360f70b5"),
"parameter" : "example",
"status" : "mystatus1",
"type" : "whattype1"
}
]
}
您不需要执行两次数据库调用,您可以使用 $lookup
(这是 mongoDB 原生的)和表达式来实现所需的功能。您也可以尝试使用 mongoose populate
(这是 mongoDB $lookup
的一种包装器)
引用: $lookup , mongoose-populate
关于node.js - 像 mongoose 一样简单的连接 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59648824/