来自两个collections如何过滤不匹配的数据
From two collections how to filter un matching data
在数据库中,我有一些样本数据作为休耕
项目(Collection 姓名)
//Object 1
{
"_id" : 1234,
"itemCode" : 3001,// (Number)
"category" : "Biscuts"
}
//Object 2
{
"_id" : 1235,
"itemCode" : 3002,// (Number)
"category" : "Health products"
}
以上是collection项中的示例数据。所以像这样,有很多 objects 具有唯一的项目代码。
订单(Collection姓名)
{
"_id" : 1456,
"customer" : "ram",
"address" : "india",
"type" : "order",
"date" : "2018/08/20",
"orderId" : "999",
"itemcode" : "3001"//('string')
}
以上为订单样本数据。即使这个 collection 也有许多 objects 具有重复的项目代码和 orderid。
在应用程序中,我们有一些名为项目未计费的选项卡。所以在这个选项卡中,我们可以看到订单中甚至没有使用过一次的项目。那么从上面的数据中,我怎样才能显示未使用的项目呢?
例如:根据以上数据,生成的项目代码应该是 3002,因为该项目甚至没有使用过一次。如何通过一个数据库查询获得输出?
您可以在 mongo 4.0 版本中使用以下聚合。
db.items.aggregate([
{ $addFields: {
itemCodeStr: {$toString: "$itemCode"}
}},
{
$lookup: {
from: "orders",
localField: "itemCodeStr",
foreignField: "itemcode",
as: "matched-orders"
}
},
{
$match: {
matched-orders: []
}
}
])
在数据库中,我有一些样本数据作为休耕 项目(Collection 姓名)
//Object 1
{
"_id" : 1234,
"itemCode" : 3001,// (Number)
"category" : "Biscuts"
}
//Object 2
{
"_id" : 1235,
"itemCode" : 3002,// (Number)
"category" : "Health products"
}
以上是collection项中的示例数据。所以像这样,有很多 objects 具有唯一的项目代码。 订单(Collection姓名)
{
"_id" : 1456,
"customer" : "ram",
"address" : "india",
"type" : "order",
"date" : "2018/08/20",
"orderId" : "999",
"itemcode" : "3001"//('string')
}
以上为订单样本数据。即使这个 collection 也有许多 objects 具有重复的项目代码和 orderid。 在应用程序中,我们有一些名为项目未计费的选项卡。所以在这个选项卡中,我们可以看到订单中甚至没有使用过一次的项目。那么从上面的数据中,我怎样才能显示未使用的项目呢? 例如:根据以上数据,生成的项目代码应该是 3002,因为该项目甚至没有使用过一次。如何通过一个数据库查询获得输出?
您可以在 mongo 4.0 版本中使用以下聚合。
db.items.aggregate([
{ $addFields: {
itemCodeStr: {$toString: "$itemCode"}
}},
{
$lookup: {
from: "orders",
localField: "itemCodeStr",
foreignField: "itemcode",
as: "matched-orders"
}
},
{
$match: {
matched-orders: []
}
}
])