![](/img/trans.png)
[英]Nodejs and Mongoose. Querying and updating object arrays inside object arrays
[英]Querying object arrays with Mongoose
假設我在 mongoose 中有這樣一個集合我有這樣一個模板
[
{
id: 123,
"arrayvalue": [
{
id: 355,
name: "jhon",
job: true
},
{
id: 155,
name: "clarck",
job: false
},
{
id: 275,
name: "orie",
job: true
},
]
}
]
我目前正在使用 nodejs express
我要做的就是獲取其值僅為 true 的對象。
我希望 output 是這樣的
[
{ id : 123,
"arrayvalue": [
{
"id": 355,
"job": true,
"name": "jhon"
},
{
"id": 275,
"job": true,
"name": "orie"
}
]
}
]
找了很多地方都沒找到,希望對項目有必要。 你可以幫忙
我使用:“貓鼬”:“^5.12.2”
選項1
演示 - https://mongoplayground.net/p/z1BwqmFh7Nq
db.collection.aggregate([
{ $unwind: "$arrayvalue" }, // break into individual documents
{ $match: { "arrayvalue.job": true } }, // match query
{
$group: { // join the document back
_id: "$_id",
arrayvalue: { $push: "$arrayvalue"}
}
}])
選項 - 2
如果您想在 JS 中執行此操作:-
const data = [{ id: 123, "arrayvalue": [{ id: 355, name: "jhon", job: true }, { id: 155, name: "clarck", job: false }, { id: 275, name: "orie", job: true }, ] }] const arr = data.map((d) => { if (d.arrayvalue) { d.arrayvalue = d.arrayvalue.filter(e => e.job === true); } return d; }); console.log(arr);
var obj ={ id: 123, arrayvalue: [ { id: 355, name: "jhon", job: true }, { id: 155, name: "clarck", job: false }, { id: 275, name: "orie", job: true }, ] }; var response = {}; for (var i = 0; i < obj.arrayvalue.length; i++) { if (obj.arrayvalue[i].job) { response[i] = obj.arrayvalue[i]; } } console.log(response);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.