regex - Mongodb use aggregate to iterate through collection -


i have collection of summaries called collectioname, , list of key words called keywords. used below code filter out summaries in collectioname contains first key word in list, , worked great.

db.collectioname.aggregate([ { $match: { summary: {$regex: keywords[1], $options:"i"} } }, { $out: "subsetfinal" } ]); 

but when started loop it, gave me aggregation error. can't figure out why.

for (var = 0; < 79; i++) {db.collectioname.aggregate([ { $match: { summary: {$regex: keywords[i], $options:"i"} } }, { $out: "subsetfinal" } ])};  

it gives me error:

$regex has string
code 16810

can help?

you use pipe-delimited regex pattern keywords this:

test documents:

db.collectioname.insert([     { summary: "a b c" },     { summary: "d e f" },     { summary: "g h i" },     { summary: "j k l" },     { summary: "m n o" } ]); 

the magic:

var keywords = ["a", "d", "j"],     regex = keywords.join("|");  db.collectioname.aggregate([      {          "$match": {              "summary": {                 "$regex": regex,                  "$options": "i"             }          }      },      { "$out": "subsetfinal" }  ]); 

the query:

db.subsetfinal.find({}, {_id:0}) 

gives

/* 0 */ {     "summary" : "a b c" }  /* 1 */ {     "summary" : "d e f" }  /* 2 */ {     "summary" : "j k l" } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -