javascript - Change MongoDB find results dynamically -
i'm using mongoose node.js.
let's have 'posts' db each document in post. each post has 'readby' array holds names of users had read post.
when i'm searching documents in db, want "change" 'readby' value show boolean value if user searching in array or not.
for example, let's these 2 documents in db:
{ "postname": "post number 1", "readby": ["tom", "john", "adam"] } { "postname": "post number 2", "readby": ["john", "adam"] }
if i'm user 'tom', want results this:
[ { "postname": "post number 1", "readby": true, }, { "postname": "post number 2", "readby": false, } ]
now, know can documents , go on each 1 of them foreach function, , use foreach again on "readby" array , change field.
i'm asking if there more efficient way in mongodb query itself, or other way in code.
if there way mongoose - better.
using mongodb $setintersection in aggregation
result :
db.collectionname.aggregate({ "$project": { "readby": { "$cond": { "if": { "$eq": [{ "$setintersection": ["$readby", ["tom"]] }, ["tom"] ] }, "then": true, "else": false } }, "postname": 1 } })
so above working first
{ $setintersection: [ [ "tom", "john", "adam"], [ "tom"] ] }, return [ "tom"] { $setintersection: [ [ "john", "adam"], [ "tom"] ] }, return [ ]
and $eq check whether setintersection
results matched ["tom"]
if yes return true
else false
Comments
Post a Comment