Select 基于 mongoid 中单个文档的键的散列数组中的值

Select the value from an array of hashes based on key from a single document in mongoid

我在 items collection 中有一个文档,例如

// Document One
{
    "_id" : ObjectId("556411af73616d0d822f0000"),
    "visibility" : [
        {
            "user_id" : ObjectId("556412bb73616d0d82310000"),
            "visible" : false
        },
        {
            "user_id" : ObjectId("556412c973616d0d82320000"),
            "visible" : true
        }
    ]
},

// Some other documents
{...}
{...}

我只想根据我提供的 user_id 为 "Document One" 获取 visible 的值(例如 ObjectId("556412bb73616d0d82310000"))。

如何?

我正在使用 mongoid 4.0.0。

谢谢。

也许你可以试试这个:

db.one.find(
   {"visibility.user_id": ObjectId("556412bb73616d0d82310000")},
   {_id: 0, "visibility.$": 1})

查询语句db.collection.find(query, projection)中,{"visibility.user_id": ObjectId("")}用于select所需项,{_id: 0, "visibility.$": 1}用于显示指定字段。 更重要的是,$运算符(投影)用于限制输出为匹配的数组。

官方文档:http://docs.mongodb.org/manual/reference/operator/projection/positional/#projection

$ The positional $ operator limits the contents of an from the query results to contain only the first element matching the query document. To specify an array element to update, see the positional $ operator for updates.

当您只需要 selected 文档中的一个特定数组元素时,在 find() 方法或 findOne() 方法的投影文档中使用 $。

您可以通过两种方式做到这一点:

1> 在投影中使用 $elemMatch$

db.collectionName.find({"visibility":{"$elemMatch":{"user_id":ObjectId("556412bb73616d0d82310000")}}},
{"visibility.$visible":1,"_id":0})

它返回结果为

"visibility" : [ { "user_id" : ObjectId("556412bb73616d0d82310000"), "visible" : false } ] 

这个 return 整个匹配数组 visibility

2> 使用 aggregation 如下:

 db.collectionName.aggregate({
   "$unwind": "$visibility"
 }, {
   "$match": {
     "visibility.user_id": ObjectId("556412bb73616d0d82310000")
   }
 }, {
   "$project": {
     "_id": 0,
     "visible": "$visibility.visible"
   }
 })

return 结果为 { "visible" : false }