Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

mongodb - Mongo DB. Find document by nested key and slice another key in the document. I use GraphQl Apollo server for handling communication with db

I have trouble to slice an array which is nested inside an object. I'm new to mongo and not sure if the model I choose for the document is most elegant one for my case. Let's say I have:

_id: 1
state: {
  state: AZ
  cities: ["a", "b", "c", "d"]
}

I tried:

 1) db.collection('states').aggregate([
          { $match: { state: 'AZ' } },
          { $project: { membersArr: { $slice: ['$cities', 0, 1] } } },
        ]);


 2) db
       .collection('states')
       .findOne({ 'state.state': 'AZ' }, { $slice: ['$cities', 0,1]})

Expected result: array of cities will be sliced!
Please help. Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  db.collection('states').findOne({ 'state.state': 'AZ' }, {'state.cities':{ $slice: [0,1]}})

With aggregation:-

db.collection('states').aggregate([
      { $match: { 'state.state': 'AZ' } },
      { $project: { 'state.cities': { $slice: ['$state.cities', 0, 1] } } },
    ]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...