从 mongodb 个查询结果集中提取字段
Extract field from mongodb query result set
如何从节点 js 中的查询响应中提取 json 字段?
我有一个问题:-
const Allposts = await Post.aggregate([pipeline])
所有帖子:-
{
_id: 1,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: 2022-04-13T17:12:28.097Z,
updatedAt: 2022-04-13T17:12:28.097Z,
__v: 0
},
{
_id: 2,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: 2022-04-13T17:12:28.097Z,
updatedAt: 2022-04-13T17:12:28.097Z,
__v: 0
},
{
_id: 3,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: 2022-04-13T17:12:28.097Z,
updatedAt: 2022-04-13T17:12:28.097Z,
__v: 0
}, and so on
我想提取 totalCount
字段并存储它的值该怎么做?
假设 totalCount
值在所有对象中都相同,您可以使用第一个索引提取第一个值
let tc = Allposts[0].totalCount;
let data = [{
_id: 1,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
updatedAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
__v: 0
},
{
_id: 2,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
updatedAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
__v: 0
},
{
_id: 3,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
updatedAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
__v: 0
}
]
let tc = data[0].totalCount;
console.log(tc);
如果您只从查询响应中得到 totalCount
字段,您可以在查询中添加 .project() 如下
const Allposts = await Post.aggregate().project("totalCount -_id");
如何从节点 js 中的查询响应中提取 json 字段?
我有一个问题:-
const Allposts = await Post.aggregate([pipeline])
所有帖子:-
{
_id: 1,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: 2022-04-13T17:12:28.097Z,
updatedAt: 2022-04-13T17:12:28.097Z,
__v: 0
},
{
_id: 2,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: 2022-04-13T17:12:28.097Z,
updatedAt: 2022-04-13T17:12:28.097Z,
__v: 0
},
{
_id: 3,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: 2022-04-13T17:12:28.097Z,
updatedAt: 2022-04-13T17:12:28.097Z,
__v: 0
}, and so on
我想提取 totalCount
字段并存储它的值该怎么做?
假设 totalCount
值在所有对象中都相同,您可以使用第一个索引提取第一个值
let tc = Allposts[0].totalCount;
let data = [{
_id: 1,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
updatedAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
__v: 0
},
{
_id: 2,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
updatedAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
__v: 0
},
{
_id: 3,
type: 'A',
source: 'B',
status: 'C',
totalCount: 7,
createdAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
updatedAt: '2022 - 04 - 13 T17: 12: 28.097 Z',
__v: 0
}
]
let tc = data[0].totalCount;
console.log(tc);
如果您只从查询响应中得到 totalCount
字段,您可以在查询中添加 .project() 如下
const Allposts = await Post.aggregate().project("totalCount -_id");