gpt4 book ai didi

MongoDB 过滤数组中的特定数据并仅返回输出中的特定字段

转载 作者:可可西里 更新时间:2023-11-01 09:57:39 26 4
gpt4 key购买 nike

我在示例集合中维护了以下结构。

{
"_id": "1",
"name": "Stock1",
"description": "Test Stock",
"lines": [
{
"lineNumber": "1",
"priceInfo": {
"buyprice": 10,
"sellprice": 15
},
"item": {
"id": "BAT10001",
"name": "CricketBat",
"description": "Cricket bat"
},
"quantity": 10
},
{
"lineNumber": "2",
"priceInfo": {
"buyprice": 10,
"sellprice": 15
},
"item": {
"id": "BAT10002",
"name": "CricketBall",
"description": "Cricket ball"
},
"quantity": 10
},
{
"lineNumber": "3",
"priceInfo": {
"buyprice": 10,
"sellprice": 15
},
"item": {
"id": "BAT10003",
"name": "CricketStumps",
"description": "Cricket stumps"
},
"quantity": 10
}
]
}

我有一个场景,我将获得 lineNumberitem.id,我需要根据 lineNumberitem.id,我只需要投影选定的字段。

预期输出如下:

{
"_id": "1",
"lines": [
{
"lineNumber": "1",
"item": {
"id": "BAT10001",
"name": "CricketBat",
"description": "Cricket bat"
},
"quantity": 10
}
]
}

注意: 我可能不会一直得到 lineNumber,如果 lineNumber 为 null 那么我应该过滤 item.id 单独得到上面提到的输出。主要目的是减少输出中的字段数量,因为集合预计会包含大量字段。

我尝试了下面的查询,

db.sample.aggregate([
{ "$match" : { "_id" : "1"} ,
{ "$project" : { "lines" : { "$filter" : { "input" : "$lines" , "as" : "line" , "cond" :
{ "$and" : [ { "$eq" : [ "$$line.lineNumber" , "3"]} , { "$eq" : [ "$$line.item.id" , "BAT10001"]}]}}}}}
])

但是我得到了所有字段,我无法排除或包含必填字段。

最佳答案

我尝试了下面的查询,它对我有用,

db.Collection.aggregate([
{ $match: { _id: '1' } },
{
$project: {
lines: {
$map: {
input: {
$filter: {
input: '$lines',
as: 'line',
cond: {
$and: [
{ $eq: ['$$line.lineNumber', '3'] },
{ $eq: ['$$line.item.id', 'BAT10001'] },
],
},
},
},
as: 'line',
in: {
lineNumber: '$$line.lineNumber',
item: '$$line.item',
quantity: '$$line.quantity',
},
},
},
},
},

])

关于MongoDB 过滤数组中的特定数据并仅返回输出中的特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47530344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com