【问题标题】:MongoDB query to retrieve a specific value from the document located in a arrayMongoDB 查询以从位于数组中的文档中检索特定值
【发布时间】:2018-10-25 13:39:26
【问题描述】:

我正在尝试使用 mongodb 在文档中发出请求。

在本文档中

{
    "_id" : ObjectId("5bd19a92da24674fdabd26b6"),
    "search" : "try",
    "name" : "try",
    "email" : "yes@gmail.com",
    "password" : "$2a$10$YIRuApqDy/L8HU7R1k2SB.aC2hqH8xFDbl3/muF7PsoN6/SGzsH4q",
    "color" : 0,
    "profil" : "",
    "banner" : "",
    "desc" : "",
    "date" : 45587899,
    "friend" : [
            {
                    "id" : ObjectId("5bcee588ae409f434d35c76c")
            }
    ],
    "groupes" : [ ]
}

我希望只获得朋友的 id,而不是所有的文档,只有 1 个朋友的 id 与我尝试这个的地方:

db.users.find({$and:[{"friend.id":"ObjectId(5bcee588ae409f434d35c76c)"},{"search":"try"}]})

它不工作,我没有结果。

谢谢你帮助我。

【问题讨论】:

标签: arrays json database mongodb


【解决方案1】:

我不能 100% 确定我是否正确理解了您的问题。您应该能够通过以下查询来查询所描述的文档:

find(
  /* query by 'search' and the specific friend-id */
  {'friend.id': ObjectId("5bcee588ae409f434d35c76c"), search: 'try'}, 

  /* return only that 'friend' element which matches the queried 'friend-id' */
  {_id:0, friend:{$elemMatch:{id:ObjectId("5bcee588ae409f434d35c76c")}}}
)

你会得到以下结果:

{
    "friend" : [ 
        {
            "id" : ObjectId("5bcee588ae409f434d35c76c")
        }
    ]
}

【讨论】:

    【解决方案2】:
    db.users.find({
        friend: {
            $elemMatch: {
                id: ObjectId("5bcee588ae409f434d35c76c")
            }
        },
        search: 'try'
    })
    

    【讨论】:

    • 你能解释一下为什么这是问题的答案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    相关资源
    最近更新 更多