当列表中某项的字段值与另一项的不同字段值匹配时查询 MongoDB 集合

Querying MondoDB collection when a field value of an item in a list matches another item's different field value

我在 mongoDB 中有一个集合,其中记录如下(示例数据),其中最新版本存储在名为“version”的字段中,并具有增量值和 _id 的副本作为历史数据项的 resourceId。这里记录 1、2、3 是具有不同版本和状态的相同记录。所以我需要找到一个项目的 id 与其他记录 recourseId 匹配并且状态与其他记录一起为“已发布”的所有记录。在这种情况下,我的输出应该只有记录 4,因为虽然记录 3 具有最高版本但状态未发布。在这种情况下,我不显示任何记录 1、2 或 3。如何使用 c#.netvb.netMongoDB 中实现?

1.  id:"11A"
    name: "Blue Block"
    status: "Published"
    version: "0"
    resourceId: ""
2.  id:"11B"
    name: "Blue Block"
    status: "Published"
    version: "1"
    resourceId: "11A"
3.  id:"11C"
    name: "Blue Block"
    status: "Draft"
    version: "2"
    resourceId: "11A"
4.  id:"11D"
    name: "Red Block"
    status: "Published"
    version: "0"
    resourceId: ""

我尝试了什么:

Public Class Toy
    Public Property ID As String
    Public Property Name As String
    Public Property Status As String
    Public Property Version As String
    Public Property ResourceID As String
End class

Private Function GetToys() As List(Of Toy)
 
  Dim listOfToys = db.GetCollection(Of BsonDocument)("Toys").Aggregate().Match(Function(x) x.GetElement("id") = x.GetElement("resourceId")).SortByDescending(Function(x) x.GetElement("version")).Group(BsonDocument.Parse("{ 'id':'$group',  'latestvalue':{$first:'$value'} }")).ToList()

  Return listOfToys
End Function

没用。不确定如何在此处添加“状态”检查。

查询需要超过标准$lookup。首先我尝试在 MongoDB Compass 中创建 pipeline 如下,然后我将其翻译成 VB.Net.

查询首先检查 属性 字段值中的三个是否存在。然后它按 version 降序对文档进行排序。然后它根据匹配 resourceId_id 对文档进行分组。然后该组被赋予一个不同的名称 latestversion。然后它根据 status 匹配新分组的文档。这是预期的结果。

MongoDBCompass 攻击管道:

[{$match: {
$and: [
{
  status: {
    $exists: true
  }
},
{
  version: {
    $exists: true
  }
},
{
  resourceId: {
    $exists: true
  }
}
]
}}, {$sort: {
      version: -1
}}, {$group: {
      _id: '$resourceId',
      latestVersion: {
            $first: '$$ROOT'
    }
 }}, {$match: {
     'latestVersion.status': {
     $eq: 'Published'
}
}}, {$replaceRoot: {
     newRoot: '$latestVersion'
}}]