我有这样的用法。我有问题在我的Mongo和一个CRUD微服务。在这里,我公开了一个API方法,通过查询params提供的I列表来获取问题。为了简单起见,用户给出了/api/questions?id=2, id=7, id=4, id = 5
然后我需要按照完全相同的顺序返回问题列表,如下所示
questions: [
{
id: 2,
prompt: "prompt one",
...
},
{
id: 7,
prompt: "prompt two",
...
},
{
id: 4,
...
},
{
id: 5
...
}
]但是请注意,这既不是ASC也不是DESC,而是任何像/api/questions?id=2, id=7, id=4, id=5这样的任意命令。
我使用org.springframework.data.mongodb.repository.MongoRepository作为我的DAO类。目前,在通过基于spring数据的存储库获取数据之后,我正在服务层中进行排序。这个解决方案奏效了。但是,我更愿意在DAO存储库级别完成这个排序,因为它的成本更低,并且不会给服务层的业务逻辑增加不必要的复杂性。相反,我可以仅仅将责任委托给DB,前提是它更有能力通过更多的优化来完成这些事情。
蒙戈的文档结构是这样的。

我可以使用spring数据来实现这一点吗?如果是这样的话,那该怎么做呢?
发布于 2017-11-18 15:48:46
如果您正在使用MongoRepository,那么创建一个扩展它的接口。示例:
public interface MyRepository extends MongoRepository<Question, String>{
@Query("{_id: { $in: ?0 } })")
List<Question> findByIds(List<String> ids, Sort sort);
}然后在您的服务类中或者在您使用存储库的任何地方。增加以下内容:
Sort sort = new Sort(Direction.ASC,"_id"); // Or DESC
List<Question> questionsById = repository.findByIds(ids, sort);当然,这里的问题是我创建的一个虚拟类,用来测试它,用您的类替换它。
好的,如果您需要输入用户订单,那么就不能使用聚合框架了。
如果我的数据库中有以下数据集按该顺序插入:
/* 1 */
{
"_id" : ObjectId("5a103a434d8a2fe38bec5c5e"),
"prompt" : "prompt one"
}
/* 2 */
{
"_id" : ObjectId("5a103a434d8a2fe38bec5c60"),
"prompt" : "prompt two"
}
/* 3 */
{
"_id" : ObjectId("5a103a434d8a2fe38bec5c62"),
"prompt" : "prompt three"
}
/* 4 */
{
"_id" : ObjectId("5a103a434d8a2fe38bec5c64"),
"prompt" : "prompt four"
}然后,聚合管道必须如下所示:
db.getCollection('questions').aggregate([{
"$match": {
"_id": {
"$in": [ObjectId("5a103a434d8a2fe38bec5c62"), ObjectId("5a103a434d8a2fe38bec5c60"), ObjectId("5a103a434d8a2fe38bec5c64"), ObjectId("5a103a434d8a2fe38bec5c5e")]
},
}
},
{
"$project": {
"orderByInputId": {
"$cond": [{
"$eq": ["$_id", ObjectId("5a103a434d8a2fe38bec5c62")]
},
1,
{
"$cond": [{
"$eq": ["$_id", ObjectId("5a103a434d8a2fe38bec5c60")]
},
2,
{
"$cond": [{
"$eq": ["$_id", ObjectId("5a103a434d8a2fe38bec5c64")]
},
3,
4
]
}
]
}
]
},
prompt: 1
}
},
// Sort the results
{
"$sort": {
"orderByInputId": 1
}
}
])我得到的结果如下:
/* 1 */
{
"_id" : ObjectId("5a103a434d8a2fe38bec5c62"),
"prompt" : "prompt three",
"orderByInputId" : 1.0
}
/* 2 */
{
"_id" : ObjectId("5a103a434d8a2fe38bec5c60"),
"prompt" : "prompt two",
"orderByInputId" : 2.0
}
/* 3 */
{
"_id" : ObjectId("5a103a434d8a2fe38bec5c64"),
"prompt" : "prompt four",
"orderByInputId" : 3.0
}
/* 4 */
{
"_id" : ObjectId("5a103a434d8a2fe38bec5c5e"),
"prompt" : "prompt one",
"orderByInputId" : 4.0
}https://stackoverflow.com/questions/47355618
复制相似问题