如何在mongo字段中存储项目符号列表或值列表

时间:2015-04-02 16:18:57

标签: mongodb

mongo集合下面有一个名为“责任”的字段。该字段的值是一个长字符串,因为它包含项目符号值,如下面的示例文档所示。有没有更好的方法来存储这个值。(而不是存储长字符串值)

{ "_id" : ObjectId("551d6f4c40cd93dd6bec7dbf"), 
  "name" : "xxxx", 
  "desc" : "xxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 
 "teamsize" : 11, 
 "location" : "xxxxx", 
 "startDate" : ISODate("2014-06-01T00:00:00Z"), 
 "endDate" : ISODate("2015-03-01T00:00:00Z"), 
 "responsibilities" : "1. xxxxxxx , 2.xxxxxx, 3.xxxxxxxx",
 "organisationName" : "xxxxxxxx"

}

1 个答案:

答案 0 :(得分:1)

您可以拆分字符串并将元素存储在数组字段中。拆分字符串需要一些正则表达式操作:

var responsibilities = "1. Jnflkvkbfjvb1  2.   Kjnfbhvjbv2  3.   kbvrjvbrjvb3 •    Jnflkvkbfjvb4  •    Kjnfbhvjbv5  •    kbvrjvbrjvb6 A.   Jnflkvkbfjvb7  B.   Kjnfbhvjbv8  C.   kbvrjvbrjvb9 I.   Jnflkvkbfjvb10  II.  Kjnfbhvjbv11  III. kbvrjvbrjvb12";

var myarray = responsibilities.split(/([0-9A-Z]+[.)]|•)\s+/);
var res_array = myarray.filter(function(el, index) {
    return index % 2 === 0;    // JavaScript is zero-based want elements with a modulo of 0 - odd numbered indexes:
});

console.log(res_array[0]);  // Jnflkvkbfjvb1
console.log(res_array[4]);  // Kjnfbhvjbv5
console.log(res_array[10]);  // Kjnfbhvjbv11

正则表达式意思是:

(              # group 1
  [0-9A-Z]+    #   any combination of digits 0-9 or letters A-Z
  [.)]         #   either a dot or a closing paren
  |            #   ...or
  •            #   a bullet sign
 )\s+          # end group 1, match any following whitespace

获得阵列后,请按照以下步骤对集合进行更新:

db.collection.update(
   { name: "xxxx" },
   { $push: { duties: { $each: res_array } } }
)