【问题标题】:Find objects in deep Mongo DB docs在深度 Mongo DB 文档中查找对象
【发布时间】:2016-05-30 17:11:50
【问题描述】:

我有一个带有团队数组的 Mongo DB 文档。团队数组中的所有对象都包含一个 user_ids 数组。如何查找包含 user_ids 包含特定对象 ID 的团队的所有文档?我正在使用 Mongoose 和 Node。

这是文档结构。例如,我如何在任何团队中找到对象 ID 为“56a60da2351195cc6be83799”的所有文档?

{
"_id" : ObjectId("56a60da3351195cc6be8379c"),
"session_id" : ObjectId("56a60da2351195cc6be83798"),
"teams" : [ 
    {
        "score" : 0,
        "user_ids" : [ 
            ObjectId("56a60da2351195cc6be83799")
        ]
    }, 
    {
        "score" : 0,
        "user_ids" : [ 
            ObjectId("56a60da2351195cc6be8379a")
        ]
    }
],
"created_at" : ISODate("2016-01-25T11:57:23.006Z") }

谢谢

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    假设你的收藏名称是collection,试试:

    db.collection.find({"teams.user_ids": ObjectId("56a60da2351195cc6be83799")})
    

    它会找到一个文档,如果存在匹配user_ids

    【讨论】:

    • 非常感谢!更新那个id怎么样?对于普通数组,我可以做 { $set: { user_ids.$ : XXX } }。这不适用于两个级别。有什么想法吗?
    • MongoDB 确实难以处理嵌套数组,但是您可以轻松地在客户端进行更新。
    【解决方案2】:

    对于嵌套数组,$in 运算符将是一个不错的选择(请参阅documentation)。

    我尝试重现您的设置并创建了一个简单的模型:

    var testSchema = mongoose.Schema({
      session_id: { type: Number },
      teams : [
        {
          score: { type: Number },
          user_ids: [{ type: Number }]
        }
      ]
    })
    
    var Test = mongoose.model("Test", testSchema);
    

    插入的演示数据:

    var test1 = new Test({
      session_id: 5,
      teams: [
        { score: 5, user_ids: [ 1, 2, 4] },
        { score: 3, user_ids: [ 2, 7, 9 ] },
        { score: 1, user_ids: [ 3 ] },
      ]
    });
    
    test1.save(function(err, t1) { console.log("test", err, t1); });
    
    var test2 = new Test({
      session_id: 1,
      teams: [
        { score: 5, user_ids: [ 11, 12 ] },
        { score: 3, user_ids: [ 1, 9 ] },
      ]
    });
    
    test2.save(function(err, t2) { console.log("test", err, t2); });
    

    获取 userId 为 2 的所有对象的查询如下所示:

    Test.find({ "teams.user_ids": { $in: [2] }}, function(err, res) {
      console.log("query:", err, res);
    });
    

    或者以更猫鼬的方式重组查询:

    Test.find()
      .where('teams.user_ids')
      .in([2])
      .then(result => { console.log(result); })
      .catch(err => { console.log(err); });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 2018-02-14
      • 2014-03-09
      • 2020-10-17
      相关资源
      最近更新 更多