代码之家  ›  专栏  ›  技术社区  ›  Pradyut Bhattacharya

使用mongodb查看结果中的子节点数据

  •  1
  • Pradyut Bhattacharya  · 技术社区  · 8 年前

    我试图在mongodb中查看子节点数据

    db.users.aggregate({$unwind: '$social'} ,  
    { $project : { name: '$name' ,fb: '$social.facebook'  }  } );
    

    我只想查看姓名和facebook字段

    但它显示数据为-

     /* 1 */
    {
    "_id" : ObjectId("583d94b42a7b4dfc334d1ab7"),
    "name" : "Person Name",
    "fb" : "www.fb.com/maria.mongodb"
    }
    
    /* 2 */
    {
    "_id" : ObjectId("583d94b42a7b4dfc334d1ab7"),
    "name" : "Person Name"
    }
    
    /* 3 */
    {
    "_id" : ObjectId("583da2a52a7b4dfc334d1ab8"),
    "name" : "Some Name",
    "fb" : "www.fb.com/some.name"
    }
    
    /* 4 */
    {
    "_id" : ObjectId("583da2a52a7b4dfc334d1ab8"),
    "name" : "Some Name"
    }
    

    如您所见,2和4数据中的数据是 没有fb字段。

    我拥有的原始数据是-

    /* 1 */
    {
    "_id" : ObjectId("583d94b42a7b4dfc334d1ab7"),
    "name" : "Person Name",
    "social" : [ 
        {
            "facebook" : "www.fb.com/maria.mongodb",
            "privacy" : true
        }, 
        {
            "twitter" : "www.tw.com/mongodb",
            "privacy" : false
        }
    ],
    "personal" : [ 
        {
            "cell_no" : "+1-99082198414",
            "privacy" : true
        }, 
        {
            "email" : "maria@mongodb.com",
            "privacy" : false
        }
    ]
     }
    
     /* 2 */
     {
    "_id" : ObjectId("583da2a52a7b4dfc334d1ab8"),
    "name" : "Some Name",
    "social" : [ 
        {
            "facebook" : "www.fb.com/some.name",
            "privacy" : true
        }, 
        {
            "twitter" : "www.tw.com/mongodb",
            "privacy" : false
        }
    ]
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   dyouberg    8 年前

    试试这个,你只需要在社交的文档上进行匹配。facebook存在于您的投影之前。

    db.users.aggregate([
        { $unwind: '$social' },
        { $match: { 'social.facebook': { $exists: true } } },
        { $project : { _id: 0, name: '$name', fb: '$social.facebook'  } }
    ]);
    

    结果如下:

    { "name" : "Person Name", "fb" : "www.fb.com/maria.mongodb" }
    { "name" : "Some Name", "fb" : "www.fb.com/some.name" }