【问题标题】:MongoDB: Return deeply nested document from it's id regardless of levelMongoDB:无论级别如何,都从其 id 返回深度嵌套的文档
【发布时间】:2023-03-28 11:23:01
【问题描述】:

我有一个包含文档的集合,这些文档由 id、名称和项目数组组成;每个文档中的数组在适用时应该嵌套相同结构的其他文档,并且文档的嵌套数组没有多少个限制(嵌套文档也可以有嵌套文档)。

使用 MongoClient 包,我正在尝试查询我的集合并根据它的 id 返回一个文档,而不管它在数据中的位置(无论是在顶层还是向下 3 层)。

到目前为止,我可以返回任何顶级数据,但我的查询没有找到任何嵌套数据。我看到过数据结构有限且一致的类似问题,但由于我的数据是动态的和多层的,我还没有找到适合这个特定问题的解决方案。

这是我的数据:

[
  {
    "_id": 1,
    "name": "Test 1",
    "items": []
  },
  {
    "_id": 2,
    "name": "Test 2",
    "items": [
      {
        "_id": 3,
        "name": "Test 3",
        "items": []
      },
      {
        "_id": 4,
        "name": "Test 4",
        "items": [
          {
            "_id": 6,
            "name": "Test 6",
            "items": []
          }
        ]
      }
    ]
  },
  {
    "_id": 5,
    "name": "Test 5",
    "items": []
  }
]

这是我的 Mongo 查询:

MongoClient.connect(connString, function(err, db) {
    var collection = db.collection('items');
    collection.findOne({_id: ObjectID("4")}, function(err, result) {
        console.log(result);
    });
    db.close();
});

结果是打算返回以下内容,但返回null:

{
  "_id": 4,
  "name": "Test 4",
  "items": [
    {
      "_id": 6,
      "name": "Test 6",
      "items": []
    }
  ]
}

谁能分享我如何按预期检索数据的解决方案?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    由于每个级别的属性都发生了变化,因此无法查询到无限数量的文档。有关可以使用的选择器列表,请参阅查询选择器 (https://docs.mongodb.com/manual/reference/operator/query/#query-selectors)。

    但是,如果可以对项目进行限制或给出深度限制,那么您可以使用如下查询:-

    db.col.find( {$or: [ { "_id" : id }, { "items._id" : id }, { "items.items._id" : id }, { "items.items.items._id" : id } ] } );
    

    如果无法给出深度限制,我建议将文档重新建模为:

    [
      {
        "_id": 1,
        "name": "Test 1"
      },
      {
        "_id": 3,
        "name": "Test 3",
        "parentId": 2
      },
      {
        "_id": 6,
        "name": "Test 6",
        "parentId": 4
      },
      {
        "_id": 4,
        "name": "Test 4",
        "parentId": 2
      },
      {
        "_id": 2,
        "name": "Test 2",
      },
      {
        "_id": 5,
        "name": "Test 5",
      }
    ]
    

    然后你可以通过 _id 查询做一个简单的查找:

    > db.collection.find({_id: 4})
    { "_id" : 4, "name" : "Test 4", "parentId" : 2 }
    

    如果您还需要保留查询的文档结构,可以使用$graphLookup 聚合阶段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      相关资源
      最近更新 更多