这是我第一次在 Java 中使用 Mongo,我在这个聚合查询中遇到了一些问题。我可以在 Mongo for Spring 中做一些简单的查询,并@Query
在我的 Repository 接口中添加注释,它扩展了MongoRepository<T, ID>
. 了解在 Spring-Data 中进行长聚合时采用哪种方法会很有帮助。
db.post.aggregate([
{
$match: {}
},
{
$lookup: {
from: "users",
localField: "postedBy",
foreignField: "_id",
as: "user"
}
},
{
$group: {
_id: {
username: "$user.name",
title: "$title",
description: "$description",
upvotes: { $size: "$upvotesBy" },
upvotesBy: "$upvotesBy",
isUpvoted: { $in: [req.query.userId, "$upvotesBy"] },
isPinned: {
$cond: {
if: { $gte: [{ $size: "$upvotesBy" }, 3] },
then: true,
else: false
}
},
file: …
Run Code Online (Sandbox Code Playgroud) 我的 Vue.js 应用程序有以下情况:
data() {
return {
data: []
}
},
async created() {
console.log('before async call')
try {
// async call ...
console.log('after async call')
this.data = // data from api call
} catch (err) {
// handle err
}
},
mounted() {
console.log('mounted')
init(this.data)
}
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,我得到:
before async call
mounted
after async call
Run Code Online (Sandbox Code Playgroud)
因此,init 方法(mounted 中的类构造函数)会使用空数组而不是来自 API 调用的数据进行调用。我想要的是同步执行事物,并且在数据可用之前不执行安装。我知道上面的问题是当包含异步代码时Vue如何执行生命周期,但是如何解决这样的问题呢?
我是 Spring Data MongoDB 的新手,我正在尝试使用 Spring Data MongoDB 在 Java 中实现聚合查询。我尝试从这个问题中进行搜索并使用 来解决它MongoTemplate
,但仍然没有结果。
我的数据格式:
[{
"_id" : ObjectId("5e1aea6c275360baf96bac29"),
"title" : "postim",
"upvotesBy" : [
"5e18b4c12753608718dfa007",
"5e19ac0f5161a4994ded1f35"
],
"file" : "test",
"description" : "description",
"postedBy" : "5e18b4c12753608718dfa007",
"createdAt" : ISODate("2020-01-12T09:44:12.119+0000"),
"_class" : "com.socialnetwork.post.Post"
},
{
"_id" : ObjectId("5e1aeaf8275360bb4bb47325"),
"title" : "postim2",
"upvotesBy" : [
"5e18b4c12753608718dfa007",
"5e19ac0f5161a4994ded1f35"
],
"file" : "test2",
"description" : "description2",
"postedBy" : "5e18b4c12753608718dfa007",
"createdAt" : ISODate("2020-01-12T09:46:32.909+0000"),
"_class" : "com.socialnetwork.post.Post"
}]
Run Code Online (Sandbox Code Playgroud)
我的查询:
db.post.aggregate([
{
$match: {}
},
{ …
Run Code Online (Sandbox Code Playgroud)