在 MongoDB 文档中查找匹配的数组项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9720342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:32:07  来源:igfitidea点击:

Find matching array items in MongoDB document

codeignitermongodb

提问by Jonathan Clark

I am developing a web app using Codeigniter and MongoDB. In the database I got a document that look like this:

我正在使用 Codeigniter 和 MongoDB 开发 Web 应用程序。在数据库中,我得到了一个如下所示的文档:

{
    "_id": {
        "$id": "4f609932615a935c18r000000"
    },
    "basic": {
        "name": "The project"
    },
    "members": [
        {
            "user_name": "john",
            "role": "user",
            "created_at": {
                "sec": 1331730738,
                "usec": 810000
            }
        },
        {
            "user_name": "markus",
            "role": "user",
            "created_at": {
                "sec": 1331730738,
                "usec": 810000
            }
        }
    ]
}

I need to search this document using both user_name and role. Right now when I am using the below code I get both. I only want to get array items matching both user_name and role.

我需要使用 user_name 和 role 搜索此文档。现在当我使用下面的代码时,我得到了两个。我只想获得匹配 user_name 和 role 的数组项。

$where = array (

    '_id' => new MongoId ($account_id), 

    'members.user_id' => new MongoId ($user_id),

    'members.role' => $role

);

$this -> cimongo -> where ($where) -> count_all_results ('accounts');

回答by JohnnyHK

This is an old question, but as of MongoDB 2.2 or so you can use the $positional operatorin a projection so that only the matched array element is included in the result.

这是一个老问题,但从 MongoDB 2.2 开始,您可以在投影中使用$位置运算符,以便结果中只包含匹配的数组元素。

So you can do something like this:

所以你可以做这样的事情:

$this->cimongo->where($where)->select(array('members.$'))->get('accounts');

回答by Spencer

This is a repeat of this question:

这是这个问题的重复:

Get particular element from mongoDB array

从 mongoDB 数组中获取特定元素

Also you might want to use $elemMatch

你也可能想使用 $elemMatch

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray

Here is the rub -- you aren't going to be able to get the array items that match because mongo is going to return the entire document if those elements match. You will have to parse out the code client side. Mongo doesn't have a way to answer, "return only the array that matches."

这就是问题所在——您将无法获得匹配的数组项,因为如果这些元素匹配,mongo 将返回整个文档。您将不得不解析代码客户端。Mongo 没有办法回答,“只返回匹配的数组”。