我有两个收藏品如下:
db.qnames.find()
{ "_id" : ObjectId("5a4da53f97a9ca769a15d49e"), "domain" : "mail.google.com", "tldOne" : "google.com", "clients" : 10, "date" : "2016-12-30" }
{ "_id" : ObjectId("5a4da55497a9ca769a15d49f"), "domain" : "mail.google.com", "tldOne" : "google.com", "clients" : 9, "date" : "2017-01-30” }和
db.dropped.find()
{ "_id" : ObjectId("5a4da4ac97a9ca769a15d49c"), "domain" : "google.com", "dropDate" : "2017-01-01", "regStatus" : 1 }我想加入这两个集合,并选择“dropDate”字段(从删除的集合)大于“date”字段(来自qname字段)的文档。因此,我使用了以下查询:
db.dropped.aggregate( [{$lookup:{ from:"qnames", localField:"domain",foreignField:"tldOne",as:"droppedTraffic"}},
{$match: {"droppedTraffic":{$ne:[]} }},
{$unwind: "$droppedTraffic" } ,
{$match: {dropDate:{$gt:"$droppedTraffic.date"}}} ])但是这个查询不会过滤dropDate < date的记录。有人能告诉我为什么会发生这种事吗?
发布于 2018-01-04 07:07:57
你没有拿到唱片的原因是
Date在集合中用作字符串,以使用比较运算符获得所需的结果,使用
new ISODate("your existing date in the collection")修改集合文档。
请注意,即使在修改了两个集合之后,也需要修改聚合查询,因为在最后的$match查询中,将比较来自同一文档的两个值。
获取所需文档的示例查询
db.dropped.aggregate([
{$lookup: {
from:"qnames",
localField:"domain",
foreignField:"tldOne",
as:"droppedTraffic"}
},
{$project: {
_id:1, domain:1,
regStatus:1,
droppedTraffic: {
$filter: {
input: "$droppedTraffic",
as:"droppedTraffic",
cond:{ $gt: ["$$droppedTraffic.date", "$dropDate"]}
}
}
}}
])发布于 2018-01-04 07:07:13
您应该使用$redact来比较同一文档的两个字段。下面的例子应该有效:
db.dropped.aggregate( [
{$lookup:{ from:"qnames", localField:"domain",foreignField:"tldOne",as:"droppedTraffic"}},
{$match: {"droppedTraffic":{$ne:[]} }},
{$unwind: "$droppedTraffic" },
{
"$redact": {
"$cond": [
{ "$lte": [ "$dropDate", "$droppedTraffic.date" ] },
"$$KEEP",
"$$PRUNE"
]
}
}
])https://stackoverflow.com/questions/48089128
复制相似问题