MongoDB:如何计算过滤后的结果集和相关集合,然后以不同的方式对其进行过滤?

时间:2020-02-09 10:27:43

标签: database mongodb

我有一个C1集合,看起来像这样(简化):

[
  // ID and other irrelevant fields omitted
  {
    "name": "A",
    "related": "Y",
    "special": "foo",
    "created" : ISODate("2020-02-07T19:36:52.757+02:00")
  },
  {
    "name": "B",
    "related": "Z",
    "special": "bar",
    "created" : ISODate("2020-02-07T19:36:52.757-06:00")
  },
  {
    "name": "C",
    "related": "X",
    "special": "baz",
    "created" : ISODate("2020-02-07T19:36:52.757+01:00")
  },
  {
    "name": "D",
    "related": "Z",
    "special": "quux",
    "created" : ISODate("2020-02-07T19:36:52.757+01:00")
  },
  // ...more records omitted...
]

还有一个集合C2,看起来像这样(再次简化):

[
  // ID and other irrelevant fields omitted
  {
    "name": "X",
    "total": 500
  },
  {
    "name": "Y",
    "total": 200
  },
  {
    "name": "Z",
    "total": 10
  },
  // ...more records omitted...
]

如何在单个查询中检索C1(例如{ "special": "foo" })中的一组过滤记录,而每个记录都有一个字段c2,其中包含来自{{ 1}}(C2等于C1.related),除了:

  • 字段C2.namelowCount中所有匹配记录的计数,其中C2
  • 字段{ total: { $lte: 100 } }midCount中所有匹配记录的计数,其中C2
  • 字段{ total: { $lte: 500, $gt: 100 } }highCount中所有匹配记录的计数,其中C2

我意识到数据库结构对于需要完成的工作很尴尬,但是我在确定数据库结构后很久才来到这里,因此目前还不能进行全面检查。实际的代码是使用Spring用J​​ava编写的。

1 个答案:

答案 0 :(得分:1)

您需要使用MongoDb聚合。

// Declare an async function
  const getData = async () => {
  // Use the await keyword to let JS know this variable has some latency so it should wait for it to be filled 
  // When the variable is fetched, use the .then() callback to carry on 
    const DataJSON = await fetch(url).then(response => 
      response.json()
    )

    return await DataJSON
  };

MongoPlayground

Spring Data允许与db.c1.aggregate([ { $match: { "special": "foo" } }, { $lookup: { from: "c2", localField: "related", foreignField: "name", as: "c2" } }, { $addFields: { lowCount: { $size: { $filter: { input: "$c2", cond: { $lte: [ "$$this.total", 100 ] } } } }, midCount: { $size: { $filter: { input: "$c2", cond: { $lte: [ "$$this.total", 500 ] } } } }, highCount: { $size: { $filter: { input: "$c2", cond: { $gte: [ "$$this.total", 500 ] } } } } } } ]) 类进行聚合(实现MongoOperations)。看看如何将此管道转换为Spring语法here

相关问题