我正在做一个使用Mongoose的MongoDB项目,在查询路径文档时遇到了挑战.每个路径文档都有如下 struct :


const locationSchema = new mongoose.Schema({
  name: { type: String, required: true },
  precedence: { type: Number, required: true },
});

const routeSchema = new mongoose.Schema({
  name: { type: String, required: true },
  locations: [{ type: locationSchema, required: true }],
});

Locations数组包含具有字段名称和优先级的子文档.

这里的优先级表示--如果某条路由位置A、B和C的优先级分别为1、2和3,则表示先覆盖位置A,然后覆盖B,然后覆盖C.

现在,我需要检索从位置A到位置B的所有路由,其中位置A的优先级小于位置B的优先级.

如果这就是数据:

[
  {
    "name": "routeA",
    "locations":[
      {
        "name":"A",
        "precedence":1
      },
            {
        "name":"B",
        "precedence":2
      },
            {
        "name":"C",
        "precedence":3
      }
      ]
  },
  {
    "name": "routeB",
    "locations":[
      {
        "name":"A",
        "precedence":2
      },
            {
        "name":"B",
        "precedence":1
      },
            {
        "name":"C",
        "precedence":3
      }
      ]
  }
]

我只能 Select 路由A.

我try 使用Aggregate,但没有得到所需的结果.

推荐答案

一种 Select 是:

  1. $match个文档,其中locations包括AB
  2. 使用$filter$sortArray仅添加包含AB的新临时数组,其中A是第一个.
  3. $match仅第一个precedence较小的文档
  4. 格式
db.collection.aggregate([
  {$match: {"locations.name": {$all: ["A", "B"]}}},
  {$addFields: {route: {
        $sortArray: {
          input: {$filter: {
              input: "$locations",
              cond: {$in: ["$$this.name", ["A", "B"]]}
          }},
          sortBy: {name: 1}
        }
  }}},
  {$match: {$expr: {
     $lt: [{$first: "$route.precedence"}, {$last: "$route.precedence"}]
  }}},
  {$unset: "route"}
])

看看它在playground example米上是如何工作的

Mongodb相关问答推荐

在MogoDB中按时间间隔分组、统计文档和获取间隔时间

在MongoDB中是否可以按递增顺序更新多个文档?

在单个mongo文档中组合数组与聚合

Tableau 与 Mongo DB Atlas by MongoDB 的连接缓存问题

分页时根据唯一字段mongodb获取数据

Mongodb聚合中基于其他字段值的多个条件的动态新字段值

更新文档中的数组时,如何在 MongoDB 和 C# 中使用 $push 更新修饰符

MongoDB 更改流副本集限制

Meteor 中的平均聚合查询

在 mongoDB 中存储 java 8 LocalDate

Node.js 数据库的抽象层

Mongodb:查询嵌套在数组中的json对象

如何在 $lookup Mongodb 的 LocalField 中将字符串转换为 objectId

Spring Mongodb @DBREF

mongodb-nodejs-driver,DeprecationWarning:collection.count 已弃用

MongoDB $or 查询

REACT 获取发布请求

如何为 node.js 中的 MongoDB 索引指定 javascript 对象中的属性顺序?

如何在 Ubuntu 上安装 mongodb-clients 最新版本?

Spring Data MongoDB - 在哪里以编程方式为 Mongo 集合创建索引?