在深Mongo DB文档中查找对象

时间:2016-05-27 19:51:12

标签: node.js mongodb mongoose

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

这是doc结构。我如何在任何一个团队中找到所有具有Object 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") }

由于

2 个答案:

答案 0 :(得分:1)

我们假设您的收藏品名称为collection,请尝试:

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

如果存在匹配user_ids

的文件,它会找到该文件

答案 1 :(得分:0)

对于嵌套数组,$ 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); });