D
D
Dmitry2210602017-11-10 16:58:23
MongoDB
Dmitry221060, 2017-11-10 16:58:23

How to index a collection by unique values?

There is a collection, for example -
[
{userID:"111111", content:"text"}, {userID:"222222", content:"text"},
{userID:"111111", content:"text"}, { userID:"111111", content:"text"},
{userID:"222222", content:"text"}, {userID:"333333", content:"text"},
{userID:"333333", content: "text"}, {userID:"111111", content:"text"}
]
Elements with the same userID need to be indexed separately. Those. the result will be -
[
{userID:"111111", content:"text", index:0}, {userID:"222222", content:"text", index:0},
{userID:"111111", content: "text"
{userID:"333333", content:"text", index:1}, {userID:"111111", content:"text", index:3}
]
I know there is a .createIndex function, but how do I compose a filter/ configure it so that it indexes all userIDs separately?
You can, of course, use
.createIndex({userID:"111111"})
.createIndex({userID:"222222"})
.createIndex({userID:"333333"})
We will get the desired result, but there are about 2000 unique id in the collection and doing it this way is not the most rational solution.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lega, 2017-11-10
@Dmitry221060

The thing is that I need to get three randomly selected "content" values, for a certain userID
So you need a regular index, not a unique one.
And to choose N random documents in Monge there is a special. command: https://stackoverflow.com/questions/24806721/mongo...

E
Eugene, 2017-11-10
@EShein

Even I do not understand what version of mongo? The createIndex method is used to create an index. In your case it would look like this..createIndex("userID: 1")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question