在一个集合中,我有一个包含数组的对象,我想在该数组中查找某些对象而不查看整个数组。我收藏中的对象如下所示:
{
"transactions": [
{"id": randint(0, 100000), "hello": randint(0, 1000)} for _ in range(100000)
]
}
Run Code Online (Sandbox Code Playgroud)
我想获取集合中所有 id 为 17 的交易。所以我创建了这个索引:
db.toto.createIndex({'transactions.id': 1})
Run Code Online (Sandbox Code Playgroud)
但是要只查看我想要的交易,我必须执行 $unwind 并且这个 unwind 仍然很慢:
db.toto.aggregate(
[
{"$match": {"transactions.id": 17}},
{"$unwind": "$transactions"},
{"$match": {"transactions.id": 17}},
]
)
Run Code Online (Sandbox Code Playgroud)
给我
[{'_id': ObjectId('5bf854f685699a394ce5ba82'),
'transactions': {'hello': 920, 'id': 17}},
{'_id': ObjectId('5bf854f685699a394ce5ba82'),
'transactions': {'hello': 446, 'id': 17}},
{'_id': ObjectId('5bf854f685699a394ce5ba84'),
'transactions': {'hello': 822, 'id': 17}},
{'_id': ObjectId('5bf854f685699a394ce5ba84'),
'transactions': {'hello': 830, 'id': 17}},
[...]
{'_id': ObjectId('5bf854f885699a394ce5ba89'),
'transactions': {'hello': 301, 'id': 17}},
{'_id': ObjectId('5bf854f985699a394ce5ba8b'),
'transactions': {'hello': 666, 'id': 17}}]
Run Code Online (Sandbox Code Playgroud)
添加第一个 $match 会使查询稍微快一点,因为它确实使用索引来查找包含我正在查找的事务的对象。但它不会使用索引来使 $unwind 更快。MongoDB 仍然遍历包含 100000 个事务的整个数组来查找我想要的事务。
查询需要 5 秒钟才能找到大约 100 个对象。而像这样db.toto.count({"transactions.id": 17})使用索引的查询只需要不到 0.1 秒。
这是我用来研究这个问题的python文件。您可以通过执行以下操作来重现该问题:
pip3 install fire pymongo
chmod +x toto_mongo.py
./toto_mongo.py insert
./toto_mongo.py create_index
time ./toto_mongo.py slow_query
Run Code Online (Sandbox Code Playgroud)
小智 2
您可以使用$lookup然后使用展开它$unwind。
您可以在后端路由中使用类似的东西。
{
$lookup: {
from: "customers",
localField: "customer",
foreignField: "_id",
as: "customerData"
}
},
{ $unwind: "$customerData" },
Run Code Online (Sandbox Code Playgroud)
您的架构如下所示:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Types.ObjectId;
var moviesSchema = new Schema({
movieId: String,
title: String,
customer: { type: Schema.Types.ObjectId, ref: 'customers', index: true },
genre: String,
releaseDate: Date,
ratings: Number,
review: String,
reviewTime: Date,
});
var movieState = mongoose.model('movies', moviesSchema);
module.exports = movieState;
Run Code Online (Sandbox Code Playgroud)