简体   繁体   中英

How can i store a bulleted list or a list of values in a mongo field

Below mongo collection has a field called 'responsibilities'. The value of this field is a long string as it contains bulleted values as shown in the sample document below). Is there any better way of storing this value.(Instead of storing long string values)

{ "_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"

}

You could split the string and store the elements in an array field. Splitting the string would require some regex manipulation:

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

Regex meaning:

(              # 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

Once you get the array then do an update on your collection as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM