Implementation tutorial of MongoDB set field matching query method, mongodb Field
MongoDB is a distributed file storage-based database. This article describes how to perform matching queries on the fields integrated in MongoDB records.
1. Create a Test Database
use testdbdb.createUser( { "user":"root", "pwd":"123456", "roles":[{"role" : "readWrite", "db":"testdb"}] } ) db.auth( { "user":"root", "pwd":"123456" } )
2. Insert test data. area_id is the set field.
db.member.insert([ { "id" : 1, "name" : "fdipzone", "area_id" : [1,2,3], }, { "id" : 2, "name" : "tom", "area_id" : [3,4], }, { "id" : 3, "name" : "polly", "area_id" : [1,3,7], }, { "id" : 4, "name" : "anslem", "area_id" : [2,4,6], }, { "id" : 5, "name" : "terry", "area_id" : [4,5,9], }])
Query inserted data
db.member.find();{ "_id" : ObjectId("59f589f5641e44b4c51cb770"), "id" : 1, "name" : "fdipzone", "area_id" : [ 1, 2, 3 ] }{ "_id" : ObjectId("59f589f5641e44b4c51cb771"), "id" : 2, "name" : "tom", "area_id" : [ 3, 4 ] }{ "_id" : ObjectId("59f589f5641e44b4c51cb772"), "id" : 3, "name" : "polly", "area_id" : [ 1, 3, 7 ] }{ "_id" : ObjectId("59f589f5641e44b4c51cb773"), "id" : 4, "name" : "anslem", "area_id" : [ 2, 4, 6 ] }{ "_id" : ObjectId("59f589f5641e44b4c51cb774"), "id" : 5, "name" : "terry", "area_id" : [ 4, 5, 9 ] }
3. Use $ in for query
Query records whose area_id contains 1
db.member.find({"area_id":{$in:[1]}});{ "_id" : ObjectId("59f589f5641e44b4c51cb770"), "id" : 1, "name" : "fdipzone", "area_id" : [ 1, 2, 3 ] }{ "_id" : ObjectId("59f589f5641e44b4c51cb772"), "id" : 3, "name" : "polly", "area_id" : [ 1, 3, 7 ] }
Note: $ in can only check whether each element in the set matches. If any element matches, a record is returned. It cannot check whether multiple elements are matched at the same time.
For example, to query records whose area_id contains both 2 and 4, use $ in to query only records whose IDs contain 2 or 4.
db.member.find({"area_id":{$in:[2,4]}});{ "_id" : ObjectId("59f58ddfa874fe2b3da340bf"), "id" : 1, "name" : "fdipzone", "area_id" : [ 1, 2, 3 ] }{ "_id" : ObjectId("59f58ddfa874fe2b3da340c0"), "id" : 2, "name" : "tom", "area_id" : [ 3, 4 ] }{ "_id" : ObjectId("59f58ddfa874fe2b3da340c2"), "id" : 4, "name" : "anslem", "area_id" : [ 2, 4, 6 ] }{ "_id" : ObjectId("59f58ddfa874fe2b3da340c3"), "id" : 5, "name" : "terry", "area_id" : [ 4, 5, 9 ] }
4. Use $ all for query
$ All: checks whether multiple elements are matched at the same time.
Query records whose area_id contains both 2 and 4
db.member.find({"area_id":{$all:[2,4]}});{ "_id" : ObjectId("59f58ddfa874fe2b3da340c2"), "id" : 4, "name" : "anslem", "area_id" : [ 2, 4, 6 ] }