查询以在mongodb中检索数组中的多个对象

问题描述:

假设我有一个如下的对象数组.

Suppose I have a array of objects as below.

"array" : [ 
    {
        "id" : 1
    }, 
    {
        "id" : 2
    }, 
    {
        "id" : 2
    }, 
    {
        "id" : 4
    }
]

如果我要从此数组中检索多个对象( {id:2} ),则聚合查询将如下所示.

If I want to retrieve multiple objects ({id : 2}) from this array, the aggregation query goes like this.

db.coll.aggregate([{ $match : {"_id" : ObjectId("5492690f72ae469b0e37b61c")}}, { $unwind : "$array"}, { $match : { "array.id" : 2}}, { $group : { _id : "$_id", array : { $push : { id : "$array.id"}}}}  ])

以上汇总的输出为

   {
        "_id" : ObjectId("5492690f72ae469b0e37b61c"),
        "array" : [ 
            {
                "id" : 2
            }, 
            {
                "id" : 2
            }
        ]
    }

现在的问题是: 1)是否可以在MongoDB中使用 find()从数组中检索多个对象?

Now the question is: 1) Is retrieving of multiple objects from an array possible using find() in MongoDB?

2)关于性能,聚合是正确的方法吗? (因为我们需要使用四个管道运算符)?

2) With respect to performance, is aggregation is the correct way to do? (Because we need to use four pipeline operators) ?

3)我们可以在之后使用Java操作(循环数组并仅保留{id:2}对象)来执行此操作吗? find({"_ id":ObjectId("5492690f72ae469b0e37b61c")})查询?因为find将一次检索文档并将其保存在RAM中.但是,如果我们使用聚合,则需要在RAM中执行四个操作以获取输出.

3) Can we use Java manipulation (looping the array and only keep {id : 2} objects) to do this after find({"_id" : ObjectId("5492690f72ae469b0e37b61c")}) query? Because find will once retrieve the document and keeps it in RAM. But if we use aggregation four operations need to be performed in RAM to get the output.

为什么我问3)的问题是:假设如果成千上万的客户端同时访问,则RAM内存将过载.如果使用Java完成,则可以减少RAM上的任务.

Why I asked the 3) question is: Suppose if thousands of clients accessing at the same time, then RAM memory will be overloaded. If it is done using Java, less task on RAM.

4) workingSet在RAM中将保留多长时间 ???

我的理解正确吗?

如果我错了,请纠正我.

Please correct me if I am wrong.

请建议我对此有正确的见识.

Please suggest me to have right insight on this..

  1. 否.您可以用$投影第一个匹配的投影,也可以投影所有的投影,或者都不投影.

  1. No. You project the first matching one with $, you project all of them, or you project none of them.

没有味道.如果必须使用此数组,则可以使用聚合来提取多个匹配元素,但是从概念上和性能方面来说,正确的解决方案是设计文档结构,这样就不会出现此问题,或者仅在很少的查询中出现其性能不是特别重要.

No-ish. If you have to work with this array, aggregation is what will allow you to extract multiple matching elements, but the correct solution, conceptually and for performance, is to design your document structure so this problem does not arise, or arises only for rare queries whose performance is not particularly important.

是.

我们没有任何信息可以使我们对这个问题给出合理的答案.相对于其余问题,这也超出了范围,应该是一个单独的问题.

We have no information that would allow us to give a reasonable answer to this question. This is also out of scope relative to the rest of the question and should be a separate question.