【问题标题】:Mongodb: How to return just the embedded document with aggregation frameworkMongodb:如何使用聚合框架仅返回嵌入文档
【发布时间】:2014-02-06 23:20:33
【问题描述】:

这是报价和投标是子文档的文档结构。我使用 mongoosejs 作为 ORM。

var user = {
    name : 'polk',
    offers: [{
        title: '1',
        tags: ['a', 'b', 'c'],
        bids: [{
            _id: 1      
            name: 'jose', 
            age: 18
        }, {
            _id: 2
            name: 'carlos', 
            age: 19
        }]
    },{
        title: '2',
        tags: ['d', 'e', 'f'],
        bids: [{
            _id: 3
            name: 'gomes', 
            age: 21
        }, {
            _id: 4
            name: 'fernando', 
            age: 31
        }]
    }]
};

我需要什么?本子文档:

{
    _id: 4
    name: 'fernando', 
    age: 31
}

使用?聚合框架。

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以使用聚合框架执行以下操作:

    db.collection.aggregate(
        {$unwind : "$offers"},
        {$unwind : "$offers.bids"},
        {$match : {"offers.bids._id" : 4}},
        {$project : {_id : "$offers.bids._id", 
                     name : "$offers.bids.name", 
                     age : "$offers.name.age"
        }}
    )
    

    【讨论】:

    • 嗨!很感谢!我这样做:db.registers.aggregate( {$match : {"_id" : ObjectId("52d93f9331065a8e76061646")}}, {$unwind: '$offers'}, {$unwind: '$offers.bids'}, {$match: {"offers.bids.name":"fernando"}}, {$project: {'_id':0, 'bid' : '$offers.bids'}});
    猜你喜欢
    • 1970-01-01
    • 2014-03-04
    • 2013-09-18
    • 1970-01-01
    • 2019-11-09
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多