简体   繁体   English

Mongodb:查询子文档数组

[英]Mongodb: Querying array of subdocuments

I have users' collection whose schema is like: 我有用户集合,其架构如下:

{
  _id: unique number,
  name: 'asdf',
  age: '12',
  gender: 'm',
  address: [
    {area: 'sdf',
     city: 'sdq', 
     state: 'wfw'},
    {area: 'asdf',
     city: 'sdfs',
     state: 'vfdwd'}
  ]
}

I want to find out the users for whom all the values of state in address should be the value I pass. 我想找出address所有state值应该是我传递的值的用户。 If even one of the state value doesn't match with the value I pass the user shouldn't be returned. 如果state值之一与我传递的值都不匹配,则不应返回用户。 I tried simple find, aggregation framework with $unwind , $match but nothing seemed to get solution. 我尝试使用$unwind$match简单的查找,聚合框架,但似乎没有解决方案。 Can you please help me out... 你能帮我一下吗...

Thanks 谢谢

PS please bear with multiple addresses for the sake of question. 附言:请为多个地址承担疑问。 :) :)

To find out if all array entries match the state "wfw", do an aggregation like the following: 要找出所有数组条目是否都与状态“ wfw”匹配,请执行以下汇总:

db.users.aggregate([
    { "$project" : {
        "test" : {
            "$allElementsTrue" : [{
                "$map" : { 
                    "input" : "$address", 
                    "as" : "a", 
                    "in" : { "$eq" : ["wfw", "$$a.state"] }
                }
            }]
        }
    } },
    { "$match" : { "test" : true } }
])

This aggregation takes each document, maps "state equals 'wfw'" over the address array to get a boolean array, and tests if the entire array is true, storing the result in `test, and then filtering the results based on test. 该汇总将获取每个文档,在地址数组上映射“状态等于'wfw'”,以获取布尔数组,然后测试整个数组是否为真,将结果存储在`test中,然后基于test过滤结果。 You will need MongoDB 2.6 for support of some of the operators. 您将需要MongoDB 2.6来支持某些操作员。

I don't know if I understand. 我不知道我是否理解。

I replicated your document. 我复制了您的文件。 When you want to retrieve an user by state you can do in many ways 当您想按state检索用户时,可以采取多种方式

If you search with single value you can do 如果您使用单一值进行搜索,则可以

db.g.find({ "address.state": "wfw" })

and retrieve an user 并检索用户

You can use $all 您可以使用$all

db.g.find( { "address.state": { $all: ["wfw","vfdwd"] } } ) // retrieve User

db.g.find( { "address.state": { $all: ["wfw","vfdwd","foo"] } } ) // don't retrieve User

or you can use $and 或者您可以使用$and

db.g.find( { $and: [ { "address.state":"wfw" },{ "address.state":"vfdwd" }] } )

But I don't know if I understand your question 但是我不知道你的问题

Update and the correct answer 更新和正确答案

db.g.find( { "address.state": { $nin: ["wfw"] } } )

Let me Know 让我知道

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM