【问题标题】:Querying MondoDB collection when a field value of an item in a list matches another item's different field value当列表中某个项目的字段值与另一个项目不同的字段值匹配时查询 MongoDB 集合
【发布时间】:2021-02-03 14:19:39
【问题描述】:

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

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 用例。

标签: c# mongodb vb.net mongodb-query mongodb-.net-driver


【解决方案1】:

查询需要的不仅仅是标准的$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'
}}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多