java 有人能帮我构建一个可以与MongoDB一起使用的@Query吗

rmbxnbpk  于 2023-09-29  发布在  Java
关注(0)|答案(2)|浏览(83)

我已经根据自己的需求设计了Java架构,但查询部分的形成却让我很纠结。
架构如下

Class AbcRequest{
List<Filters> filters;
}

Class Filters{
String abcCode;
List<String> abcType;
}

Class abcController{
getFilters(List<String>someList, boolean status, AbcRequest request){
for(Filters filter: request.getFilters(){
String abcCode = filter.getAbcCode();
List<String> abcTypes = filter.getAbcType();
  }
 }
}

现在我想将这些值传递给存储库,并根据它从DB中获取所需查询的列表。
我的查询应该有这样的条件:where((someList in('a ','b')and status='false' and abcCode='8' and abcType in('done ','pending')OR(someList in('a ','b')and status='false' and abcCode='6' and abcType in('pending '))
如何编写MongoDB @Query来从存储库方法中获取这样的查询。它是许多“AND”和“OR”的组合,例如:--其中(a AND b AND c AND d)OR(a AND e AND f AND d)
我知道如何在@Query中使用简单的OR:-例如构建一个查询(其中A=10 OR B=10)@Query('$or':[{A:10},{B:10}])
但是我想构建的查询有点复杂,我正在努力解决它。我也不想使用Criteria,因为我必须处理返回类型。最好是使用@Query,我也被指示使用@Query。
任何帮助将不胜感激。

6ie5vjzr

6ie5vjzr1#

你可以试试这个:

Query query = new Query();
        Criteria criteria = new Criteria();
        Criteria a = new Criteria();
        a.andOperator(Criteria.where("someList").in(Arrays.asList("A","B")),Criteria.where(
                "status").is(false),Criteria.where("abcCode").is(6),....)
        // B is the same as a
        Criteria b = new Criteria();
        //...
        
        criteria.orOperator(a,b);
        query.addCriteria(criteria);
jv4diomz

jv4diomz2#

We specify the targetUserId variable with the user_id you want to filter by.

We add a $match stage at the beginning of the aggregation pipeline to filter documents with the specified user_id.

The rest of the aggregation pipeline remains the same as before, calculating the sum of account balances for the specified user.

We then check if the result contains data for the specified user and print the user's total balance, or print a message if the user is not found or has no accounts.

Make sure to replace 'mongodb://localhost:27017/your-database-name' with your actual MongoDB connection string and adjust the schema to match your data structure if needed.

// Connect to the MongoDB database using the Liquid ORM's Database module
const db = await Database.connect('mongodb');

// Access the "bank_accounts" collection within the database
const accountsCollection = db.collection('bank_accounts');

// Define an aggregation pipeline to filter and group account data
const aggregationPipeline = [
  {
    // Stage 1: Match documents where the user_id matches the currently targetUserId 
    $match: {
      user_id: targetUserId,
    },
  },
  {
    // Stage 2: Group the matched documents by user_id and calculate the total balance
    $group: {
      _id: '$user_id', // Group by user_id
      totalBalance: { $sum: { $toDouble: '$account_balance' } }, // Calculate the sum of account_balance
    },
  },
];

// Execute the aggregation pipeline and store the result in the "result" variable
const result = await accountsCollection.aggregate(aggregationPipeline).toArray();

console.log("result" ,result);

// Check if there are accounts found for the user
if (result.length > 0) {
  // Log the total account balance for the user
  console.log('Total account balance:', result[0].totalBalance);

  // Update the "total_balance" field in the UserModel for the user
  await UserModel.query().where("slug", request.user().slug).update({"total_balance": result[0].totalBalance});
} else {
  // Log a message indicating that no accounts were found for the user
  console.log('No accounts found.');
}

相关问题