在 MongoDB 数据库中按数组中的 _id 来查找?
若要按数组中的 _id 查找,请使用聚合并避免使用 find()。我们先使用文档创建集合 -
> db.demo414.insertOne(
... {
... "_id": "110",
... "details":[
... {
... "StudentName":"John",
... "StudentMarks":56
... },
... {
... "StudentName":"Robert",
... "StudentMarks":98
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : "110" }借助 find() 方法显示集合中的所有文档 -
> db.demo414.find();
这将产生以下输出 -
{ "_id" : "110", "details" : [ { "StudentName" : "John", "StudentMarks" : 56 }, { "StudentName" : "Robert", "StudentMarks" : 98 } ] }以下是按数组中的 _id 查找的查询 -
> db.demo414.aggregate([{$unwind: "$details"}, {$match:{"details.StudentMarks" :56}}] )这将产生以下输出 -
{ "_id" : "110", "details" : { "StudentName" : "John", "StudentMarks" : 56 } }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP