MongoDB聚合从嵌套数组中获取最后一个元素的字段

时间:2020-04-30 16:02:37

标签: mongodb mongodb-query aggregation-framework

我想聚合并仅显示嵌套数组中的最后一个对象 这是我的数据库:

[{
  "firstName": "Shaun",
  "salary": [
    {
    "id":1,
    "rate": 250,
    },
    {
    "id":2,
     "rate": 290,
    }
  ]
},{
  "firstName": "Julian",
  "salary": [
    {
    "id":1,
     "rate": 750,      
    },
    {
    "id":2,
     "rate": 760,      
    },
    {
    "id":3,
     "rate": 790,      
    },
  ]
}
}]

我想要的结果是:

{"firstName": "Shaun", "rate":290},{"firstName": "Julian", "rate":790}

1 个答案:

答案 0 :(得分:1)

尝试下面的聚合查询,该查询使用$arrayElemAt从数组import React,{Component} from 'react'; import { Platform, StyleSheet, StatusBar, View, Text, TextInput, Button, Alert } from 'react-native'; import {editAp} from '../pages/func'; import firebase from 'firebase'; if (!firebase.apps.length) { firebase.initializeApp({}); } class Edit1 extends Component { constructor(props){ super(props); this.state = { email:this.props.navigation.state.params.email, password:this.props.navigation.state.params.password, keyis:this.props.navigation.state.params.keyis, }; } submit1=()=>{ console.log(this.props.navigation.state.params.keyis) //Modified path here also firebase.database().ref('/users1/').child(firebase.auth().currentUser.uid).update(({email:this.state.email,password:this.state.password})) Alert.alert('Action!', 'user updated'); } render(){ return ( <View style={styles.container}> <Text>Edit Here</Text> <TextInput style={{marginTop:20, height:40, borderColor:'gray', borderWidth:1}} onChangeText={email=>this.setState({email})} value={this.state.email}/> <TextInput style={{marginTop:20, height:40, borderColor:'gray', borderWidth:1}} onChangeText={password=>this.setState({password})} value={this.state.password}/> <TextInput style={{marginTop:20, height:40, borderColor:'gray', borderWidth:1}} onChangeText={keyis=>this.setState({keyis})} value={this.state.keyis}/> <Button title='Submit' onPress={this.submit1} /> </View> ); } } const styles = StyleSheet.create({ container: { flex:1, justifyContent: 'center', backgroundColor: '#fff', padding: 30, }, }); export default Edit1; 中获取最后一个元素:

salary.rate

测试: mongoplayground