MongoDB在集合列表中搜索每个字典 [英] MongoDB search for each dict in list in collection

查看:45
本文介绍了MongoDB在集合列表中搜索每个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个collection包含listdicts,我想搜索是否有dict包含两个特定的key:values.

I have a collection containing a list of dicts and I want to search if any dict contains two specific key:values.

例如,我想find_one字典中包含特定的名字和姓氏.这是我的收藏:

So for example I want to find_one where a dict contains a specific first and last names. This is my collection:

{
"names": [
    {
        "firstName": "bob",
        "lastName": "jones",
        "age": "34",
        "gender": "m"
    },
    {
        "firstName": "alice",
        "lastName": "smith",
        "age": "56",
        "gender": "f"
    },
    {
        "firstName": "bob",
        "lastName": "smith",
        "age": "19",
        "gender": "m"
    },          
  ]
}

我想查看是否有以鲍勃·史密斯为名字和姓氏的记录,我正在搜索为:

I want to see if there is a record with bob smith as first and last names, I am searching this as:

first = 'bob'
last = 'smith'

nameExists = db.user.find_one({'$and':[{'names.firstName':first,'names.lastName':last}]})

此查询是否为鲍勃·史密斯检索一条记录?

Would this query retrieve the one record for bob smith?

推荐答案

虽然提到确实 $and 运算符,无论哪种形式,这都不是您想要的查询.请考虑以下内容:

While it is mentioned that indeed the $and operator is not required, in either form this is not the query that you want. Consider the following:

db.user.find_one({ 'names.firstName': 'alice','names.lastName': 'jones' })

实际上,这匹配给定记录,因为同时存在"firstName"等于"alice"且"lastName"值等于"jones"的两个元素.但是,当然,这里的问题很简单,因为数组中没有实际的元素同时具有两个值的子文档.

This in fact does match the given record as there are both elements with "firstName" equal to "alice" and "lastName" values equal to "jones". But of course the problem here is simple in that there is no actual element in the array that has a sub-document for both of those values.

为了匹配数组元素包含两个"给定条件的位置,您需要使用 $elemMatch 运算符.这会将查询条件应用于数组的元素".

In order to match where an array element contains "both" the criteria given, you need to use the $elemMatch operator. This applies the query condition to the "elements" of the array.

db.user.find_one({ 
    'names': { '$elemMatch': { 'firstName': 'alice','lastName': 'smith' }
})

当然,如果您尝试使用"alice"和"jones",则不会匹配,因为没有元素实际包含该操作.

And of course if you tried "alice" and "jones" then that would not match as no element actually contains that operation.

这篇关于MongoDB在集合列表中搜索每个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆