![](/img/trans.png)
[英]Mongodb: find documents with array where all elements exist in query array, but document array can be smaller
[英]mongodb query document matching condition in all the array elements?
我正在開發游戲應用程序。
在一種情況下,我需要在子數組(SelectionData)的所有元素中找到所有滿足條件的文檔。
//模型
import mongoose from 'mongoose';
const User_Selection = mongoose.Schema({
UserSelectionID: { type: String, default: "" },
SelectionData: [
{
_id: false,
match_id: { type: String, default: "" },
selected_option: { type: String, default: "" },
selected_points: { type: Number, default: 0 },
Whether_Points_Calculated: { type: Boolean, default: false },
Points_Collected: { type: Number, default: 0 }
}
],
Opponent_Details: {
USERID: { type: String, default: "" },
DisplayName: { type: String, default: "" }
},
Whether_Final_Points_Calculated: { type: Boolean, default: false },
Total_Game_Points: { type: Number, default: 0 },
Status: { type: Boolean, default: true },
created_at: { type: Date, default: null },
updated_at: { type: Date, default: null }
}, { collection: 'User_Selection' });
export default mongoose.model('User_Selection', User_Selection);
我希望在所有數組元素中找到所有滿足條件的文檔(“ SelectionData.Whether_Points_Calculated” == true)。
應該像這樣
const cursor = async() => {
return new Promise((resolve, reject) => {
User_Selection.find({
SelectionData: { Whether_Points_Calculated: true }
})
. then(result => {
resolve(result)
})
. catch(err => {
reject(err)
})
}
這必須工作:
db.getCollection('User_Selection')。find({“ SelectionData”:{“ $ elemMatch”:{“ Whether_Points_Calculated”:true}}})
下面的腳本為我工作。
db.collection.find({
"SelectionData": {
"$not": {
"$elemMatch": {
"Whether_Points_Calculated": {
"$eq": false
}
}
}
}
})
游樂場鏈接
db.collection.aggregate([
{"$match":{"cards":{"$exists":true}}},
{$project: {
"output": {$filter: {
input: '$cards' ,
as: 'arrayElement',
cond: {"$and":[{$eq: ['$$arrayElement.Whether_Points_Calculated', true]}]}
}}
}}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.