MongoDB查找子文档数组

时间:2017-08-16 10:53:40

标签: mongodb mongoose aggregation-framework

我希望检索我的子文档中没有点击

值的所有_id
{
    "_id" : ObjectId("59786f1238894a1344e1d61a"),
    "products" : [ 
        {
            "dateAdd" : ISODate("2017-07-26T10:31:04.334Z"),
            "_id" : ObjectId("59786f4df9f1c5cb764f9769"),
            "click" : "12"
        }, 
        {
            "dateAdd" : ISODate("2017-07-26T12:46:12.397Z"),
            "_id" : ObjectId("59788eebf9f1c5cb764f976f")
        }, 
        {
            "dateAdd" : ISODate("2017-07-26T12:49:54.614Z"),
            "_id" : ObjectId("59786fc0f9f1c5cb764f976a")
        }, 
        {
            "dateAdd" : ISODate("2017-07-26T12:52:42.742Z"),
            "_id" : ObjectId("5978909af9f1c5cb764f9770")
        }, 
        {
            "dateAdd" : ISODate("2017-08-07T12:34:57.462Z"),
            "_id" : ObjectId("59885e71e5ef9cdbf9c51fa2")
        }
    ]
}

{
    "_id" : ObjectId("59786f1238894a1344e1d61b"),
    "products" : [ 
        {
            "dateAdd" : ISODate("2017-07-26T12:46:12.397Z"),
            "_id" : ObjectId("59788eebf9f1c5cb764f976f")
        }, 
        {
            "dateAdd" : ISODate("2017-07-26T12:49:54.614Z"),
            "_id" : ObjectId("59786fc0f9f1c5cb764f976a")
        }, 

    ]
}

我想恢复这些值: 59788eebf9f1c5cb764f976f, 59786fc0f9f1c5cb764f976a, 5978909af9f1c5cb764f9770, 59885e71e5ef9cdbf9c51fa2

有了这个请求:

db.users.find({
    "products.click": {
        $exists: false 
    }
}, {
    "products._id": 1,
    "_id": 0
});

我刚收到了第二份文件的_id。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

find()命令将返回符合条件的所有文档,但不允许您过滤这些文档中的子文档数组。为了过滤子文档数组,您必须使用聚合管道。使用项目+过滤器是一个选项,除了$cond不支持$exists运算符,因此您必须$unwind product数组,以便您可以通过{{1}过滤它然后$match结果。

此示例将返回4个“文档”,每个文档包含$project

product._id

回复示例:

db.users.aggregate([
    // unwind the products array
    { $unwind: '$products' },
    // filter out any products which have a populated 'click' attribute 
    { $match: { 'products.click': { $exists: false } } },
    // only select the product id
    { $project: { _id: 0, 'products._id': 1 } }
])

如果您希望在一个文档中返回选定的产品ID ...

{
    "products" : {
        "_id" : ObjectId("59788eebf9f1c5cb764f976f")
    }
},
{
    "products" : {
        "_id" : ObjectId("59786fc0f9f1c5cb764f976a")
    }
},
{
    "products" : {
        "_id" : ObjectId("5978909af9f1c5cb764f9770")
    }
},
{
    "products" : {
        "_id" : ObjectId("59885e71e5ef9cdbf9c51fa2")
    }
}

...然后将一个组步骤添加到聚合管道:

{
    "_id" : ObjectId("59786f1238894a1344e1d61a"),
    "productIds" : [ 
        {
            "_id" : ObjectId("5978909af9f1c5cb764f9770")
        }, 
        {
            "_id" : ObjectId("59885e71e5ef9cdbf9c51fa2")
        }, 
        {
            "_id" : ObjectId("59786fc0f9f1c5cb764f976a")
        }, 
        {
            "_id" : ObjectId("59788eebf9f1c5cb764f976f")
        }
    ]
}