简体   繁体   English

在mongodb中使用objectId作为数组

[英]Using objectId as an array in mongodb

In javascript we can find the location of a specific string within an array using indexOf of 在javascript中,我们可以使用indexOf找到数组中特定字符串的位置

> ["aa","bb"].indexOf("bb")
1 

I want to do the same with objectIds in mongodb for example 我想对mongodb中的objectIds做同样的事情

> ids= db.foo1.distinct('_id');
[
        ObjectId("50d38d775f2b6c6e3393d6b0"),
        ObjectId("50d38d835f2b6c6e3393d6b1")
]
> id0=db.foo1.findOne()._id
ObjectId("50d38d775f2b6c6e3393d6b0")

I am looking for a way to do something like ids.indexOf(id0) that will give me the location of id0 within ids. 我正在寻找一种方法来执行类似ids.indexOf(id0)的操作 ,它将在id中为我提供id0的位置。 I can convert everything to strings and then use the indexOf but I was hoping to find a simpler way to do this. 我可以将所有内容转换为字符串然后使用indexOf但我希望找到一种更简单的方法来执行此操作。

I don't think there's a one-liner for this and you'd need to use a for loop: 我不认为这有一个单行,你需要使用for循环:

for (var i=0; i<ids.length; i++) { 
    if (ids[i].equals(id0)) { ixOfId0 = i; break; } 
}

If the list doesn't change frequently (or is only added to), consider just adding the documents with an index: { i: 0, r: ObjectId('....') } , where the i field represents the index. 如果列表不经常更改(或仅添加到列表中),请考虑仅添加带索引的文档: { i: 0, r: ObjectId('....') } ,其中i字段表示索引。

Then db.foo1.find( { 'list.r' : ObjectId('...') }) . 然后db.foo1.find( { 'list.r' : ObjectId('...') }) The result would have the index by looking at the field i in the resulting document. 通过查看结果文档中的字段i ,结果将具有索引。

But, if the list is long, this is always going to be an O(N) operation as it has to search through every array element to find the match. 但是,如果列表很长,这总是一个O(N)操作,因为它必须搜索每个数组元素以找到匹配。 You may need to create an index to improve performance. 您可能需要创建索引以提高性能。

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

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