开发者

Difference between stored array and new array in mongodb

I am new to mongodb.

I have开发者_Python百科 the following data stored in mongodb

    { "_id" : ObjectId("4"), "uid" : "1", "friendsIds" : [ "2", "3" ] }

Case 1: Now, I have new set of friendsIds ["2","3","4"]

I want to compare the both the sets, and get the value which is not stored in database. In this case, I want to get 4

Case 2: Now, I have new set of friendsIds ["3","4"]

I want to compare the both the sets, and get the value which is stored in database but not in the new set. In this case, I want to get 2

Can the Case 2 be done using mapReduce?

How to achieve both the cases in mongodb?


For case 1, it looks like you need [$addToSet][1]. Take a look at the $each example.

For case 2, there is no such server-side function. Just bring back the document and compare client-side.

What action are you doing that you just want the 2 and not everything else?


if you have two arrays

a = [ "2", "3" ]
b = ["2","3","4"]

in ruby :

a-b = ["4"]


This can be done in the aggregation framework using its set operators:

> db.foo.insert({"friendsIds" : [ "2", "3"]})
WriteResult({ "nInserted" : 1 })

> db.foo.aggregate([ {$project: {diff: {$setDifference: [["2","3","4"], '$friendsIds']}}} ])
{ "_id" : ObjectId("53490a53a0e3abbe0dd0c21c"), "diff" : [ "4" ] }

> db.foo.aggregate([ {$project: {diff: {$setDifference: ['$friendsIds', ["3","4"]]}}} ])
{ "_id" : ObjectId("53490a53a0e3abbe0dd0c21c"), "diff" : [ "2" ] }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜