mongodb中存储数组和新数组的区别

发布于 2024-11-05 02:46:17 字数 502 浏览 0 评论 0原文

我是 mongodb 的新手。

我在 mongodb 中存储了以下数据

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

情况 1: 现在,我有一组新的 FriendsIds ["2","3","4"]

我想比较这两个集合,并获取未存储在数据库中的值。在本例中,我想要得到 4

情况 2: 现在,我有一组新的 FriendsIds ["3","4"]

我想比较这两个集合,并获取存储在数据库中但不存储在新集合中的值。在这种情况下,我想得到2

情况2可以使用mapReduce完成吗?

mongodb中这两种情况如何实现?

I am new to mongodb.

I have 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谈场末日恋爱 2024-11-12 02:46:17

对于情况 1,您似乎需要 [$addToSet][1]。看一下 $each 示例。

对于情况2,没有这样的服务器端功能。只需带回文档并在客户端进行比较即可。

您正在做什么操作,您只想要 2 而不是其他一切?

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?

攒眉千度 2024-11-12 02:46:17

如果 ruby​​ 中有两个数组

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

a-b = ["4"]

if you have two arrays

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

in ruby :

a-b = ["4"]
萤火眠眠 2024-11-12 02:46:17

这可以在聚合框架中使用其 集合运算符 来完成:

> 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" ] }

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" ] }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文