有没有办法用嵌入式数组查询MongoDB集合,以返回数组中元素的偏移量

时间:2015-06-16 05:30:08

标签: arrays mongodb offset

鉴于学校藏品中有以下文件:

{
    _id: 1,
    zipcode: "63109",
    students: [
        { name: "john", school: 102, age: 10 },
        { name: "jess", school: 102, age: 11 },
        { name: "jeff", school: 108, age: 15 }
    ]
}
{
    _id: 2,
    zipcode: "63110",
    students: [
        { name: "ajax", school: 100, age: 7 },
        { name: "achilles", school: 100, age: 8 },
    ]
}
{
    _id: 3,
    zipcode: "63109",
    students: [
        { name: "ajax", school: 100, age: 7 },
        { name: "achilles", school: 100, age: 8 },
    ]
}
{
    _id: 4,
    zipcode: "63109",
    students: [
        { name: "barney", school: 102, age: 7 },
        { name: "ruth", school: 102, age: 16 },
    ]
}

以下是MongoDB文档中的示例查询:

db.schools.find( { zipcode: "63109" },
             { students: { $elemMatch: { school: 108 } } } )

它将返回如下结果:

{ "_id" : 1, "students" : [ { "name" : "jeff", "school" : 108, "age" : 15 } ] }

我的问题是如何得到这样的结果:

{ "_id" : 1, "students" : [ { "name" : "jeff", "school" : 108, "age" : 15, "offset" : 2 } ] }

如您所见,此结果会添加字段偏移量。有人曾尝试过这个吗?

1 个答案:

答案 0 :(得分:0)

以下是解决您问题的方法:

 db.schools.find( { zipcode: "63109" },
    { _id : 1 , students : 1 }).forEach( function(doc){
   var arr = doc.students;
   for( var index = 0 ; index < arr.length ; index++ )
     {
        if( arr[index].school == 108 )
         {
        var d = arr[index];
        d["offset"] = index;
         }
         else
         {
        arr.splice(index, 1);

         }
      }
    });