Mongo db Query以过滤文档中的嵌套对象数组 [英] Mongo db Query to filter nested array of objects in document

查看:57
本文介绍了Mongo db Query以过滤文档中的嵌套对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文件

<代码>{"userid": "5a88389c9108bf1c48a1a6a7","email": "abc@gmail.com","lastName": "abc","firstName": "xyz","__v": 0,朋友们": [{"userid": "5a88398b9108bf1c48a1a6a9","ftype": "SR","状态": "接受","_id": ObjectId("5a9585b401ef0033cc8850c7")},{"userid": "5a88398b9108bf1c48a1a6a91111","ftype": "SR","状态": "接受","_id": ObjectId("5a9585b401ef0033cc8850c71111")},{"userid": "5a8ae0a20df6c13dd81256e0","ftype": "SR",状态":待定","_id": ObjectId("5a9641fbbc9ef809b0f7cb4e")}]},{"userid": "5a88398b9108bf1c48a1a6a9",朋友们": [{ }],"lastName": "123","firstName": "xyz",......},{"userid": "5a88398b9108bf1c48a1a6a91111",朋友们": [{ }],"lastName": "456","firstName": "xyz",...}

  • 第一次查询

这里我想从朋友数组中获取 userId,其状态等于接受".即

 [5a88398b9108bf1c48a1a6a9,5a88398b9108bf1c48a1a6a91111]

  • 第二次查询

之后,我必须对同一个集合进行另一个查询,以获取第一个查询中返回的每个用户 ID 的详细信息.最终查询将返回 [5a88398b9108bf1c48a1a6a9,5a88398b9108bf1c48a1a6a91111] 的详细信息两个用户 ID 即

<预><代码>[{用户 ID": "5a88398b9108bf1c48a1a6a9",姓氏":123",名字":xyz"},{用户名":5a88398b9108bf1c48a1a6a91111",姓氏":456",名字":xyz"}]

到目前为止我已经尝试过

 Users.find ({'_id':5a88389c9108bf1c48a1a6a7,"friends.status":'ACCEPT'}, (error, users) => {})或者Users.find ({'_id':5a88389c9108bf1c48a1a6a7, 朋友: { $elemMatch: { status: 'ACCEPT' } } }, (error, users) => {})

解决方案

使用聚合框架的$map$filter 操作符来处理任务.$filter 将根据指定条件过滤朋友数组,即状态应等于 "ACCESS"$map 会将过滤后的数组中的结果转换为所需的格式.

对于第二个查询,附加一个 $lookup 管道步骤,它对用户集合进行自联接,以检索与前一个管道中的 id 匹配的文档.

运行以下聚合操作将生成所需的数组:

User.aggregate([{ "$match": { "friends.status": "ACCEPT" } },{$项目":{用户":{$地图":{输入": {$过滤器":{"input": "$friends","as": "el","cond": { "$eq": ["$$el.status", "ACCEPT"] }}},"as": "项目","in": "$$item.userid"}}} },{$查找":{"from": "用户","as": "用户","localField": "用户","foreignField": "用户名"} },]).exec((错误,结果) => {如果(错误)抛出错误;控制台日志(结果[0].用户);});

I have the following document

{
    "userid": "5a88389c9108bf1c48a1a6a7",
    "email": "abc@gmail.com",
    "lastName": "abc",
    "firstName": "xyz",
    "__v": 0,
    "friends": [{
        "userid": "5a88398b9108bf1c48a1a6a9",
        "ftype": "SR",
        "status": "ACCEPT",
        "_id": ObjectId("5a9585b401ef0033cc8850c7")
    },
    {
        "userid": "5a88398b9108bf1c48a1a6a91111",
        "ftype": "SR",
        "status": "ACCEPT",
        "_id": ObjectId("5a9585b401ef0033cc8850c71111")
    },
    {
        "userid": "5a8ae0a20df6c13dd81256e0",
        "ftype": "SR",
        "status": "pending",
        "_id": ObjectId("5a9641fbbc9ef809b0f7cb4e")
    }]
},
{
    "userid": "5a88398b9108bf1c48a1a6a9",
    "friends": [{ }],
    "lastName": "123",
    "firstName": "xyz",
    .......
},
{
    "userid": "5a88398b9108bf1c48a1a6a91111",
    "friends": [{ }],
    "lastName": "456",
    "firstName": "xyz",
    ...
}   

  • First Query

Here I want to get userId from friends array ,which having status equals to "ACCEPT". ie

 [5a88398b9108bf1c48a1a6a9,5a88398b9108bf1c48a1a6a91111] 

  • Second Query

After that, I have to make another query on the same collection to get details of each userid returned in the first query. final Query will return details of [5a88398b9108bf1c48a1a6a9,5a88398b9108bf1c48a1a6a91111] both userid ie

[
        {
         userid" : "5a88398b9108bf1c48a1a6a9",
         "lastName" : "123",
         "firstName" : "xyz"
         },
       {
         "userid" : "5a88398b9108bf1c48a1a6a91111",
          "lastName" : "456",
           "firstName" : "xyz"
       }
   ]

I have tried so far with

 Users.find ({'_id':5a88389c9108bf1c48a1a6a7,"friends.status":'ACCEPT'}, (error, users) => {})  
   or 


 Users.find ({'_id':5a88389c9108bf1c48a1a6a7, friends: { $elemMatch: { status: 'ACCEPT' } } }, (error, users) => {})

解决方案

Use the aggregation framework's $map and $filter operators to handle the task. $filter will filter the friends array based on the specified condition that the status should equal "ACCESS" and $map will transform the results from the filtered array to the desired format.

For the second query, append a $lookup pipeline step which does a self-join on the users collection to retrieve the documents which match the ids from the previous pipeline.

Running the following aggregate operation will produce the desired array:

User.aggregate([
    { "$match": { "friends.status": "ACCEPT" } },
    { "$project": {
            "users": {
                "$map": {
                    "input": {
                        "$filter": {
                            "input": "$friends",
                            "as": "el",
                            "cond": { "$eq": ["$$el.status", "ACCEPT"] }
                        }
                    },
                    "as": "item",
                    "in": "$$item.userid"
                }
            }
    } },
    { "$lookup": {  
        "from": "users",
        "as": "users",
        "localField": "users",
        "foreignField": "userid"
    } },
]).exec((err, results) => {
    if (err) throw err;
    console.log(results[0].users); 
});

这篇关于Mongo db Query以过滤文档中的嵌套对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆