Mongo Query根据相同的字段值和未过期的字段值来获取文档



我有一些集合共享,共享集合中有字段sharedWith、expiryTime。

sharedWith字段是一个数组,用于指定已与这些用户共享,它包含用户的ID。

sharedWith : [NumberLong(11),NumberLong(22),NumberLong(33)]

我需要获取那些与同一用户进行了多次共享的文档,这意味着输出应该返回多个具有相同sharedWith值的共享文档和未过期的文档:

// condition to check whether document has been expired or not
currentTime < expiryTime // means the sharing document has not been expired

currentTime:(今天的当前时间(

expiryTime:(expiryTime是共享集合中的字段(

示例:

A 
{sharedWith : [NumberLong(123),NumberLong(456)],
expiryTime : ISODate("2021-07-03T06:22:29.021Z")
},
B 
{sharedWith : [NumberLong(456)],
expiryTime : ISODate("2021-07-03T06:22:29.021Z")
},
C 
{sharedWith : [NumberLong(123456)],
expiryTime : ISODate("2021-07-03T06:22:29.021Z")
},
D
{sharedWith : [NumberLong(111111)],
expiryTime : ISODate("2021-06-03T06:22:29.021Z")
},

这种情况下的输出将仅为A和B,因为两者都有公共的sharedWith字段值NumberLong(456(,并且由于今天的时间(currentTime:1 July(小于expiryTime而未过期。

注意:如果集合B的currentTime>=expiryTime意味着如果它已过期,则不应返回任何输出,因为在这种情况下,文档A或C不能单独返回,因为输出必须包含多个具有类似sharedWith字段值的共享文档,即使它没有过期。文档D超出范围,因为它自今天时间起已过期>D.到期时间

我如何更新下面的查询来实现这一点。非常感谢

db.getCollection('sharing').aggregate([
{
$addFields: { time: { $lt: ["$currentTime", "$expiryTime"] } }
},
{ 
$match: { time: true } 
},
{ $group: { 
// Group by fields to match on sharedWith
_id: { sharedWith: "$a"},
// Count number of matching docs for the group
count: { $sum:  1 },

// Save the _id for matching docs
docs: { $push: "$_id" }
}},
// Limit results to duplicates (more than 1 match) 
{ $match: {
count: { $gt : 1 }
}}
]);

这是最后一个查询,但我认为它不是一个AND条件,我只想要那些sharedWith值相同且currentTime<到期时间

下面的查询解决了这个问题。。。$unvent用于将数组拆分为各个字段,以便$group在共享上工作

db.getCollection('sharing').aggregate([
{ 
$match: { "expiryTime":{"$gte": ISODate()}  } 
},
{ $unwind: "$sharedWith"},
{ $group: { 
// Group by fields to match on sharedWith
_id: "$sharedWith",
// Count number of matching docs for the group
count: { $sum:  1 },
// Save the _id for matching docs
docs: { $push: "$_id" }
}},
// Limit results to duplicates (more than 1 match) 
{ $match: {
count: { $gt : 1 }
}}
]);

最新更新