如何从 MongoDB 的对象数组中获取项?
若要从对象数组中获取项,可以使用 aggregate()。我们创建一个包含文档的集合 −
> db.demo459.insertOne( ... { "_id" : 1, ... "Information" : [ ... { ... "Name" : "Chris", ... "_id" : new ObjectId(), ... "details" : [ ... "HR" ... ] ... }, ... { ... ... "Name" : "David", ... "_id" : new ObjectId(), ... "details" : [ ... "Developer" ... ] ... }, ... { ... ... "Name" : "Bob", ... "_id" : new ObjectId(), ... "details" : [ ... "Account" ... ] ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : 1 }
使用 find() 方法显示集合中的所有文档 −
> db.demo459.find();
这会生成以下输出 −
{ "_id" : 1, "Information" : [ { "Name" : "Chris", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95c9"), "details" : [ "HR" ] }, { "Name" : "David", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95ca"), "details" : [ "Developer" ] }, { "Name" : "Bob", "_id" : ObjectId("5e7ef4a7dbcb9adb296c95cb"), "details" : [ "Account" ] } ] }
以下是 MongoDB 中从对象数组获取项的查询 −
> db.demo459.aggregate([ ... { $unwind: '$Information' }, ... { $unwind: '$Information.details' }, ... { $match: { 'Information.Name': { $in: ["Chris","Bob"]} } }, ... { $group: { _id: null, detailList: { $addToSet: '$Information.details' } } }, ... ])
这会生成以下输出 −
{ "_id" : null, "detailList" : [ "Account", "HR" ] }
广告