欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > MongoDB - 比较查询操作符$eq | 数组查询操作符 $eleMatch

MongoDB - 比较查询操作符$eq | 数组查询操作符 $eleMatch

2024/10/24 7:28:35 来源:https://blog.csdn.net/qq_42764468/article/details/140742359  浏览:    关键词:MongoDB - 比较查询操作符$eq | 数组查询操作符 $eleMatch

文章目录

    • 1. $eq 比较查询操作符
        • 1.1 基本类型字段
        • 1.2 嵌入式文档字段
        • 1.3 数组字段
    • 2. $eleMatch 数组查询操作符
        • 2.1 基本类型数组字段
        • 2.2 基本类型数组字段
        • 2.3 嵌入式文档数组字段
        • 2.4 嵌入式文档数组字段

1. $eq 比较查询操作符

$eq 操作符匹配字段值等于指定值的文档。

db.colletion.find({{ <field>: { $eq: <value> } }
})

$eq 运算符等同于下面的形式,但 <value> 是正则表达式的情况除外。

db.colletion.find({{ field: <value> }
})
1.1 基本类型字段

构造测试数据 :

db.inventory.drop()db.inventory.insertMany( [{ _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] },{ _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] },{ _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] },{ _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] },{ _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }
] )

查询 qty=20 的所有文档:

db.inventory.find({qty: {$eq: 20}
})db.inventory.find({qty: 20
})
// 1
{"_id": 2,"item": {"name": "cd","code": "123"},"qty": 20,"tags": ["B"]
}// 2
{"_id": 5,"item": {"name": "mn","code": "000"},"qty": 20,"tags": [["A","B"],"C"]
}
@Document(collection = "inventory")
@Data
public class Inventory {@Idprivate int id;private Item item;private int qty;private List<Object> tags;@Datapublic static class Item {private String name;private String code;}
}@Test
public void queryTest() {//构造查询条件Query query = new Query();query.addCriteria(Criteria.where("qty").is(20));//执行查询 List<Inventory> inventoryList = mongoTemplate.find(query, Inventory.class);inventoryList.forEach(System.out::println);//Inventory(id=2, item=Inventory.Item(name=cd, code=123), qty=20, tags=[B])//Inventory(id=5, item=Inventory.Item(name=mn, code=000), qty=20, tags=[[A, B], C])
}
1.2 嵌入式文档字段

构造测试数据 :

db.inventory.drop()db.inventory.insertMany( [{ _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] },{ _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] },{ _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] },{ _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] },{ _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }
] )

查询 “item.name”=“ab” 的所有文档:

db.inventory.find({"item.name": {$eq: "ab"}
})db.inventory.find({"item.name": "ab"
})
// 1
{"_id": 1,"item": {"name": "ab","code": "123"},"qty": 15,"tags": ["A","B","C"]
}
@Test
public void queryTest() {//构造查询条件Query query = new Query();query.addCriteria(Criteria.where("item.name").is("ab"));//执行查询List<Inventory> inventoryList = mongoTemplate.find(query, Inventory.class);inventoryList.forEach(System.out::println);//Inventory(id=1, item=Inventory.Item(name=ab, code=123), qty=15, tags=[A, B, C])
}
1.3 数组字段

构造测试数据 :

db.inventory.drop()db.inventory.insertMany([{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 },{ "_id" : 2, "item" : "abc2", description: "product 2", qty: 200 },{ "_id" : 3, "item" : "xyz1", description: "product 3", qty: 250 },{ "_id" : 4, "item" : "VWZ1", description: "product 4", qty: 300 },{ "_id" : 5, "item" : "VWZ2", description: "product 5", qty: 180 }
])

查询 tags 数组包含 “A” 的所有文档:

db.inventory.find({"tags": {$eq: "A"}
})db.inventory.find({"tags": "A"
})
// 1
{"_id": 1,"item": {"name": "ab","code": "123"},"qty": 15,"tags": ["A","B","C"]
}// 2
{"_id": 3,"item": {"name": "ij","code": "456"},"qty": 25,"tags": ["A","B"]
}// 3
{"_id": 4,"item": {"name": "xy","code": "456"},"qty": 30,"tags": ["B","A"]
}
@Test
public void queryTest() {//构造查询条件Query query = new Query();query.addCriteria(Criteria.where("tags").is("A"));//执行查询List<Inventory> inventoryList = mongoTemplate.find(query, Inventory.class);//打印inventoryList.forEach(System.out::println);//Inventory(id=1, item=Inventory.Item(name=ab, code=123), qty=15, tags=[A, B, C])//Inventory(id=3, item=Inventory.Item(name=ij, code=456), qty=25, tags=[A, B])//Inventory(id=4, item=Inventory.Item(name=xy, code=456), qty=30, tags=[B, A])
}

2. $eleMatch 数组查询操作符

$elemMatch 操作符匹配包含数组字段的文档,该字段至少有一个元素与所有指定的查询条件匹配。

db.collection.find({ arrayField: { $elemMatch: { condition1, condition2 } } })
2.1 基本类型数组字段

构造测试数据:

db.student.drop()db.student.insertMany([{ _id: 1, scores: [ 82, 85, 88 ] },{ _id: 2, scorse: [ 75, 88, 89 ] }
])

查询 scores 数组中至少包含一个大于等于80并且小于85的文档:

db.student.find({ scores: { $elemMatch: { $gte: 80, $lt: 85 } } 
})
// 1
{"_id": 1,"scores": [82,85,88]
}
@Data
@Document(collection = "students")
public class Student {@Idprivate int id;private List<Integer> scores;
}@Test
public void queryTest() {// 构建查询条件Query query = new Query();Criteria criteria = Criteria.where("scores").elemMatch(Criteria.where("$gte").is(80).and("$lt").is(85));query.addCriteria(criteria);// 执行查询List<Student> student = mongoTemplate.find(query, Student.class, "student");student.forEach(System.out::println);//Student(id=1, scores=[82, 85, 88])
}
2.2 基本类型数组字段

构造测试数据:

db.user.drop()db.user.insertMany([{ name: "Alice", age: 25, email: "alice@example.com", hobbies: ["reading", "writing", "music"] },{ name: "John", age: 30, email: "John@qq.com", hobbies: ["reading", "gaming", "traveling"] },{ name: "Jane", age: 25, email: "Jane@qq.com", hobbies: ["sports", "music", "cooking"] },{ name: "Mike", age: 35, email: "Mike@qq.com", hobbies: ["reading", "writing", "painting"] }
]) 

查询age>=30 并且 hobbies 数组中包含 reading 的文档:

db.student.find({ age: { $gte: 30 }, hobbies: { $elemMatch: { $eq: "reading" } }
})
// 1
{"_id": ObjectId("66a4ab82f074c9a04808d562"),"name": "John","age": 30,"email": "John@qq.com","hobbies": ["reading","gaming","traveling"]
}// 2
{"_id": ObjectId("66a4ab82f074c9a04808d564"),"name": "Mike","age": 35,"email": "Mike@qq.com","hobbies": ["reading","writing","painting"]
}
@Data
@Document(collection = "user")
public class User {@Idprivate String id;private String name;private Integer age;private String email;private List<String> hobbies;public User(String name,Integer age,String email,List<String> hobbies){this.name = name;this.age = age;this.email = email;this.hobbies = hobbies;}
}@Test
public void queryTest() {// 构建查询条件Query query = new Query();Criteria criteria = Criteria.where("age").gte(30).and("hobbies").elemMatch(Criteria.where("$eq").is("reading"));query.addCriteria(criteria);// 执行查询List<User> userList = mongoTemplate.find(query, User.class, "user");userList.forEach(System.out::println);//User(id=66a4ab82f074c9a04808d562, name=John, age=30, email=John@qq.com, hobbies=[reading, gaming, traveling])//User(id=66a4ab82f074c9a04808d564, name=Mike, age=35, email=Mike@qq.com, hobbies=[reading, writing, painting])
}
2.3 嵌入式文档数组字段

构造测试数据:

db.survey.drop()db.survey.insertMany( [{ "_id": 1, "results": [ { "product": "abc", "score": 10 },{ "product": "xyz", "score": 5 } ] },{ "_id": 2, "results": [ { "product": "abc", "score": 8 },{ "product": "xyz", "score": 7 } ] },{ "_id": 3, "results": [ { "product": "abc", "score": 7 },{ "product": "xyz", "score": 8 } ] },{ "_id": 4, "results": [ { "product": "abc", "score": 7 },{ "product": "def", "score": 8 } ] },{ "_id": 5, "results": { "product": "xyz", "score": 9 } }
] )

查询 results 数组中 product=“def” 的文档:

db.survey.find({ results: { $elemMatch: { product: "def" } }
})db.survey.find({ "results.product": "def" }
)
// 1
{"_id": 4,"results": [{"product": "abc","score": 7},{"product": "def","score": 8}]
}
@Data
@Document(collection = "survey")
public class Survey {@Idprivate int id;private List<Result> results;@Datapublic class Result {private String item;private int score;}
}@Test
public void queryTest() {// 构建查询条件Query query = new Query();Criteria criteria = Criteria.where("results").elemMatch(Criteria.where("product").is("def"));query.addCriteria(criteria);// 执行查询List<Survey> surveys = mongoTemplate.find(query, Survey.class);surveys.forEach(System.out::println);//Survey(id=4, results=[Survey.Result(item=null, score=7), Survey.Result(item=null, score=8)])
}
2.4 嵌入式文档数组字段

查询 results 数组中 product=xyz,score>=8 的文档:

db.survey.find({ results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } }
})
// 1
{"_id": 3,"results": [{"product": "abc","score": 7},{"product": "xyz","score": 8}]
}
@Test
public void queryTest() {// 构建查询条件Query query = new Query();Criteria criteria = Criteria.where("results").elemMatch(Criteria.where("product").is("xyz").and("score").gte(8));query.addCriteria(criteria);// 执行查询List<Survey> surveys = mongoTemplate.find(query, Survey.class);surveys.forEach(System.out::println);//Survey(id=3, results=[Survey.Result(item=null, score=7), Survey.Result(item=null, score=8)])
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com