Mongodb嵌套查找

Mongodb嵌套查找,mongodb,mongodb-query,Mongodb,Mongodb Query,我的数据库模式有点像 { "_id" : ObjectId("1"), "createdAt" : ISODate("2017-03-10T00:00:00.000+0000"), "user_list" : [ { "id" : "a", "some_flag" : 1, }, { "id" : "b", "som

我的数据库模式有点像

{ 
    "_id" : ObjectId("1"), 
    "createdAt" : ISODate("2017-03-10T00:00:00.000+0000"), 
    "user_list" : [
        {
            "id" : "a", 
            "some_flag" : 1,  
        }, 
        {
            "id" : "b",
            "some_flag" : 0, 
        }
    ]
}
我想做的是获取文档,其中id是b&用户b的some_标志是0

我的问题是

db.collection.find({
  'createdAt': {
    $gte: new Date()
  },
  'user_list.id': 'b',
  'user_list.some_flag': 1
}).sort({
  createdAt: 1
})
当我在shell中运行查询时。它返回id为1的文档(它不应该返回id为1,因为b的某个_标志的值为0)

这里发生的事情是

查询“user\u list.id”:user\u id与嵌套对象匹配,其中“id”:b

'user\u list.some\u flag':1与嵌套对象的某个\u flag匹配,其中“id”:a(此处某个\u flag的值为1)

我应该做哪些修改来比较同一嵌套对象的id和some_标志


另外,数据量相当大&使用聚合将成为性能瓶颈

您需要尝试以下方法:

db.collection.find({
    'createdAt': {
        $gte: new Date()
    },
    user_list: {
        $elemMatch: {
            id: 'b',
            some_flag: 1
        }
    }
}).sort({
  createdAt: 1
});

这将只匹配用户列表条目,其中_id为b,someflag为1

您需要尝试以下操作:

db.collection.find({
    'createdAt': {
        $gte: new Date()
    },
    user_list: {
        $elemMatch: {
            id: 'b',
            some_flag: 1
        }
    }
}).sort({
  createdAt: 1
});

这将只匹配用户列表条目,其中_id为b,someflag为1

您应该使用
$elemMatch
,否则
mongoDB
查询将独立应用于数组项,因此,在您的情况下,
'user\u list.some_flag:'1
将与id为
a
的数组项相匹配,
'user\u list.id':'b'
将与id为
b
的数组项相匹配。因此,基本上,如果要使用
逻辑查询数组字段,请使用
$elemMatch
,如下所示:

db.collection.find({
  'createdAt': {
    $gte: new Date()
  },
  user_list: {$elemMatch: {id: 'b', some_flag: 1}} // will only be true if a unique item of the array fulfill both of the conditions.
}).sort({
  createdAt: 1
})

您应该使用
$elemMatch
否则
mongoDB
查询将独立应用于数组项,因此在您的情况下
'user\u list.some\u flag':1
将与id为
a
的数组项匹配,
'user\u list.id':'b'
将与id为
b的数组项匹配。因此,基本上,如果要使用
逻辑查询数组字段,请使用
$elemMatch
,如下所示:

db.collection.find({
  'createdAt': {
    $gte: new Date()
  },
  user_list: {$elemMatch: {id: 'b', some_flag: 1}} // will only be true if a unique item of the array fulfill both of the conditions.
}).sort({
  createdAt: 1
})

使用$elemMatch将只查找所有比较属性都匹配的条目,因此在您的示例中,我给出的查询将返回0个条目,因为它们都没有_id:'b'和一些_标志:1op告诉查询返回不应该返回的项,并且用户给出的记录仅用于抽样,正如问题中所提到的那样。所以,主要的想法是展示
$elemMatch
的用法,并解释为什么常规查询不起作用。很抱歉,我的意思是将该注释附加到下面的答案中。他们已经解释了他们的查询做错了什么,所以他们似乎理解问题的这一部分。谢谢你的更深入的描述,谢谢。我明白了。使用$elemMatch只会找到所有属性都匹配的条目,因此在您的示例中,我给出的查询将返回0个条目,因为它们都没有_id:'b'和一些_标志:1op告诉查询返回不应该返回的项,并且用户提供的记录也只是用于问题中提到的采样。所以,主要的想法是展示
$elemMatch
的用法,并解释为什么常规查询不起作用。很抱歉,我的意思是将该注释附加到下面的答案中。他们已经解释了他们的查询做错了什么,所以他们似乎理解问题的这一部分。谢谢你的更深入的描述,谢谢。我得到了它。