MongoDB 数组中的字段限制

MongoDB fields limitation in array

我正在寻找一种方法 - 如果可能的话,即使现在也不会 - 只是 return 保存在 mongodb 中的列表的一部分。

让我们看看我当前的文档:

{
    _id : 'MyId',
    name : 'a string',
    conversations : [
        {
            user : 'Mike',
            input : 'Some input'
        },
        {
            user : 'Stephano',
            input : 'some other input'
        }
    ]

}

我现在想做的是这样的:

var myOutput;
myOutput = db.my_collection.find(
{
    _id : 'MyId',
    'conversations.user' : 'Mike'
}, {
    _id : 1,
    name : 1,
    conversations : {
        $where : {
            user : 'Mike'
        }
    }
});

目标只是取回对话数组项,其中 user 的值为 Mike

这在 MongoDB 中仍然可行吗?在 mongoDB.

的字段限制文档中未找到任何参考

你知道aggregation pipeline吗?

db.my_collection.aggregate([
    { "$match": { "_id": "MyId"}}, { "$unwind": "$conversations"}, 
    { "$match": {"conversations.user": "Mike"}}
])

输出

{ 
    "_id" : "MyId", 
    "name" : "a string", 
    "conversations" : 
    { 
        "user" : "Mike", 
        "input" : "Some input" 
    } 
}

在投影中使用 $ positional operator

> db.my_collection.find({ "_id" : "MyId", "conversations.user" : "Mike" },
                      { "_id" : 1, "name" : 1, "conversations.$" : 1 })
{
    "_id" : 'MyId',
    "name" : 'a string',
    "conversations" : [
        { "user" : 'Mike', "input" : 'Some input' }
    ]
}

这只投影第一个匹配的数组元素。