简体   繁体   English

MongoDB具有唯一值的多个数组

[英]MongoDB multiple arrays with unique values

I've run into a slight dilemma creating the schema and setting up my database the "right" way. 创建模式并以“正确”的方式设置数据库时,我遇到了一个小难题。 I have a collection that contains objects which holds 4 different arrays. 我有一个包含包含4个不同数组的对象的集合。 The objects in the collection entries looks similar to: 收集条目中的对象看起来类似于:

itemInCollection{
    ...
    theObj: {arr1: ["user1685", "user5342"], arr2: ["user1432"], arr3: [], arr4: ["user1632", "user2312", "user6452"]},
    ...
}

The schema I made already requires all array items to be unique, but I also want none of the arrays to contain the same entry as another. 我创建的架构已经要求所有数组项都是唯一的,但是我也希望没有一个数组包含与另一个数组相同的条目。 I also need to sometimes move an item that's already in one array to another array (and of course delete the entry from the old array because none of the arrays should contain the same entry). 有时,我还需要将一个数组中已经存在的项移动到另一个数组中(当然,从旧数组中删除该条目,因为所有数组都不应该包含相同的条目)。 This is obviously not the best way to keep track of something like this, or is it? 显然,这不是跟踪此类事件的最佳方法,不是吗?

What I have so far is 4 queries that check each array individually for a certain entry, and another query that adds the entry to the corresponding array if no entry was found... and ANOTHER query that would delete the entry that might have been found in another before adding it to a different array. 到目前为止,我有4个查询,它们分别检查每个数组中的某个条目,以及另一个查询,如果没有找到条目,则将该条目添加到相应的数组中。还有另一个查询,它将删除可能已经找到的条目。在另一个之前,将其添加到另一个数组。

Is there a better way to set up the database to keep track of something like this? 有没有更好的方法来设置数据库来跟踪这样的事情? Or is there a dynamic way of querying multiple arrays instead of using 6-7 different queries? 还是有一种动态的方式来查询多个数组,而不是使用6-7个不同的查询?

Thanks to all in advance for you time and help :) 提前感谢大家的时间和帮助:)

You could structure your "user" data as subdocuments instead of as strings like this: 您可以将“用户”数据构造为子文档,而不是像这样的字符串:

itemInCollection{
    ...
    theObj: [
        { userid: "user1685", type: "arr1" },
        { userid: "user5342", type: "arr1" },
        { userid: "user1432", type: "arr2" },
        { userid: "user1632", type: "arr4" },
        { userid: "user2312", type: "arr4" },
        { userid: "user6452", type: "arr4" }
    ],
    ...
}

With this structure in place, it should be easier to ensure uniqueness (at this stage, unfortunately, there is no way to ensure uniqueness of a particular field inside an array - see this link ). 有了这种结构,应该更容易确保唯一性(不幸的是,在现阶段,没有办法确保数组中特定字段的唯一性-请参阅此链接 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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