如何用Mongodb复杂条件查询数组内成员?
PHPz
PHPz 2017-04-28 09:04:07
0
2
612
[{
    "_id" : ObjectId("55f181e43fdda0be857daaf4"),
    "form_info" : [ 
        {
            "val" : "王思聪",
            "id" : "1"
        }, 
        {
            "val" : "13800138000",
            "id" : "2"
        }
    ],
    "tags" : [],
    "__v" : 0
},
{
    "_id" : ObjectId("55f181e43fdda0f48578acf4"),
    "form_info" : [ 
        {
            "val" : "李丽珍",
            "id" : "1"
        }, 
        {
            "val" : "13934438010",
            "id" : "2"
        }
    ],
    "tags" : [],
    "__v" : 0
}]

如果我想筛选form_info数组内符合 成员对象内id为1,val王思聪id为2,val13800138000 的记录。

即结果是:

[{
    "_id" : ObjectId("55f181e43fdda0be857daaf4"),
    "form_info" : [ 
        {
            "val" : "王思聪",
            "id" : "1"
        }, 
        {
            "val" : "13800138000",
            "id" : "2"
        }
    ],
    "tags" : [],
    "__v" : 0
}]

该怎么写好? 谢谢大大们

PHPz
PHPz

学习是最好的投资!

reply all(2)
漂亮男人

Can you take a look at how your record is stored in the database? This is it:

db.test6.insert(
{"test":[{
    "_id" : ObjectId("55f181e43fdda0be857daaf4"),
    "form_info" : [ 
        {
            "val" : "王思聪",
            "id" : "1"
        }, 
        {
            "val" : "13800138000",
            "id" : "2"
        }
    ],
    "tags" : [],
    "__v" : 0
},
{
    "_id" : ObjectId("55f181e43fdda0f48578acf4"),
    "form_info" : [ 
        {
            "val" : "李丽珍",
            "id" : "1"
        }, 
        {
            "val" : "13934438010",
            "id" : "2"
        }
    ],
    "tags" : [],
    "__v" : 0
}]})

Or is each subdocument in the array an independent record? If it really works like what you showed above, then if you check _id directly, you will get the only record. If according to my understanding, then execute this query:

> db.test6.find({"test._id":ObjectId("55f181e43fdda0be857daaf4")},{"test.$":1}).pretty();
{
    "_id" : ObjectId("55f255aef566c6baf2af1fac"),
    "test" : [
        {
            "_id" : ObjectId("55f181e43fdda0be857daaf4"),
            "form_info" : [
                {
                    "val" : "王思聪",
                    "id" : "1"
                },
                {
                    "val" : "13800138000",
                    "id" : "2"
                }
            ],
            "tags" : [ ],
            "__v" : 0
        }
    ]
}

That’s it

刘奇

I am learning mongodb and try to answer some questions on sf.

This is a query for mongodb’s embedded array. If the index is known, you can use numeric index query.

Use array index to match fields of embedded documents

So the query can be written like this:

db.user.find({'form_info.0.id': '1', 'form_info.0.val': '王思聪', 'form_info.1.id': '2', 'form_info.1.val': '13800138000'})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!